Java 实例 - 获取线程id

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

Main.java 文件

  1. public class Main extends Object implements Runnable {
  2. private ThreadID var;
  3. public Main(ThreadID v) {
  4. this.var = v;
  5. }
  6. public void run() {
  7. try {
  8. print("var getThreadID =" + var.getThreadID());
  9. Thread.sleep(2000);
  10. print("var getThreadID =" + var.getThreadID());
  11. } catch (InterruptedException x) {
  12. }
  13. }
  14. private static void print(String msg) {
  15. String name = Thread.currentThread().getName();
  16. System.out.println(name + ": " + msg);
  17. }
  18. public static void main(String[] args) {
  19. ThreadID tid = new ThreadID();
  20. Main shared = new Main(tid);
  21. try {
  22. Thread threadA = new Thread(shared, "threadA");
  23. threadA.start();
  24. Thread.sleep(500);
  25. Thread threadB = new Thread(shared, "threadB");
  26. threadB.start();
  27. Thread.sleep(500);
  28. Thread threadC = new Thread(shared, "threadC");
  29. threadC.start();
  30. } catch (InterruptedException x) {
  31. }
  32. }
  33. }
  34. class ThreadID extends ThreadLocal {
  35. private int nextID;
  36. public ThreadID() {
  37. nextID = 10001;
  38. }
  39. private synchronized Integer getNewID() {
  40. Integer id = new Integer(nextID);
  41. nextID++;
  42. return id;
  43. }
  44. protected Object initialValue() {
  45. print("in initialValue()");
  46. return getNewID();
  47. }
  48. public int getThreadID() {
  49. Integer id = (Integer) get();
  50. return id.intValue();
  51. }
  52. private static void print(String msg) {
  53. String name = Thread.currentThread().getName();
  54. System.out.println(name + ": " + msg);
  55. }
  56. }

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

  1. threadA: in initialValue()
  2. threadA: var getThreadID =10001
  3. threadB: in initialValue()
  4. threadB: var getThreadID =10002
  5. threadC: in initialValue()
  6. threadC: var getThreadID =10003
  7. threadA: var getThreadID =10001
  8. threadB: var getThreadID =10002
  9. threadC: var getThreadID =10003