开发者社区> 问答> 正文

Java 实例 - 获取线程id

Java 实例 - 获取线程id

展开
收起
问问小秘 2020-02-13 17:54:22 1266 0
1 条回答
写回答
取消 提交回答
  • 以下实例演示了如何使用 getThreadId() 方法获取线程id:

    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); } } 以上代码运行输出结果为:

    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
    
    2020-02-13 17:54:37
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
多IO线程优化版 立即下载