zoukankan      html  css  js  c++  java
  • java 获取线程id

    如何获取正在运行的线程的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
  • 相关阅读:
    Go实现线程池
    Go语言工程结构
    Go语言示例-函数返回多个值
    Go语言参数中的三个点是干什么的
    go语言示例-Timer计时器的用法
    Go语言的类型转化
    iOS 修改通讯录联系人地址(address)崩溃原因分析
    tableview小结-初学者的问题
    Objective-C总Runtime的那点事儿(一)消息机制
    论坛源码推荐(11.6):iPhone6/6 plus屏幕适配Demo,Java代码转Objective-C
  • 原文地址:https://www.cnblogs.com/firstdream/p/6807675.html
Copyright © 2011-2022 走看看