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 =10001threadB: in initialValue()threadB: var getThreadID =10002threadC: in initialValue()threadC: var getThreadID =10003threadA: var getThreadID =10001threadB: var getThreadID =10002threadC: var getThreadID =10003
以上就是Java获取线程ID的实例的详细内容,更多关于Java获取线程ID的资料请关注好吧啦网其它相关文章!
相关文章:
1. Docker容器如何更新打包并上传到阿里云2. IntelliJ IDEA导入项目的方法3. 删除docker里建立容器的操作方法4. IntelliJ IDEA创建web项目的方法5. chat.asp聊天程序的编写方法6. 使用 kind 和 Docker 启动本地的 Kubernetes环境7. Android webview注入JS代码 修改网页内容操作8. CSS Hack大全-教你如何区分出IE6-IE10、FireFox、Chrome、Opera9. AJAX实现数据的增删改查操作详解【java后台】10. 详解php中implode explode serialize json msgpack性能对比