1. 程式人生 > 程式設計 >Java獲取執行緒ID的例項

Java獲取執行緒ID的例項

以下例項演示瞭如何使用 getThreadId() 方法獲取執行緒id:

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);
 }
}

以上程式碼執行輸出結果為:

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

以上就是Java獲取執行緒ID的例項的詳細內容,更多關於Java獲取執行緒ID的資料請關注我們其它相關文章!