发布日期:2015-11-03 13:28 来源: 标签: 编程语言 Java教程 getThreadId() java实例
本章我们主要学习如何使用 getThreadId() 方法获取线程id?下面我们就做一下具体讲解,希望大家多多支持中国站长网络学院。

以下实例演示了如何使用 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