Rumah > Java > javaTutorial > teks badan

Java 实例 - 获取线程id

黄舟
Lepaskan: 2016-12-27 13:34:53
asal
1750 orang telah melayarinya

以下实例演示了如何使用 getThreadId() 方法获取线程id:

/*
 author by w3cschool.cc
 Main.java
 */public class Main extends Object implements Runnable {
  private ThreadID var;

  public Main(ThreadID v) {
    this.var = v;
  }

  public void run() {
    try {
      print("var getThreadID =" + var.getThreadID());
      Thread.sleep(2000);
      print("var getThreadID =" + var.getThreadID());
    } catch (InterruptedException x) {
    }
  }

  private static void print(String msg) {
    String name = Thread.currentThread().getName();
    System.out.println(name + ": " + msg);
  }

  public static void main(String[] args) {
    ThreadID tid = new ThreadID();
    Main shared = new Main(tid);

    try {
      Thread threadA = new Thread(shared, "threadA");
      threadA.start();

      Thread.sleep(500);

      Thread threadB = new Thread(shared, "threadB");
      threadB.start();

      Thread.sleep(500);

      Thread threadC = new Thread(shared, "threadC");
      threadC.start();
    } catch (InterruptedException x) {
    }
  }}class ThreadID extends ThreadLocal {
  private int nextID;

  public ThreadID() {
    nextID = 10001;
  }

  private synchronized Integer getNewID() {
    Integer id = new Integer(nextID);
    nextID++;
    return id;
  }


  protected Object initialValue() {
    print("in initialValue()");
    return getNewID();
  }

  public int getThreadID() {
    Integer id = (Integer) get();
    return id.intValue();
  }

  private static void print(String msg) {
    String name = Thread.currentThread().getName();
    System.out.println(name + ": " + msg);
  }}
Salin selepas log masuk

以上代码运行输出结果为:

threadA: in initialValue()
threadA: var getThreadID =10001
threadB: in initialValue()
threadB: var getThreadID =10002
threadC: in initialValue()
threadC: var getThreadID =10003
threadA: var getThreadID =10001
threadB: var getThreadID =10002
threadC: var getThreadID =10003
Salin selepas log masuk

 以上就是Java 实例 - 获取线程id的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan