时间:2021-05-20
以下实例演示了如何使用 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
以上就是Java获取线程ID的实例的详细内容,更多关于Java获取线程ID的资料请关注其它相关文章!
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了Python进程,多进程,获取进程id,给子进程传递参数操作。分享给大家供大家参考,具体如下:线程与线程之间共享全局变量,进程之间不能共享全局变量
本文承接上一篇文章《Java多线程实例详解(一)》。四.Java多线程的阻塞状态与线程控制上文已经提到Java阻塞的几种具体类型。下面分别看下引起Java线程阻
本文实例讲述了Java线程之守护线程(Daemon)用法。分享给大家供大家参考。具体如下:守护线程(Daemon)Java有两种Thread:“守护线程Daem
本文实例分析了Java线程调度之线程休眠用法。分享给大家供大家参考。具体分析如下:Java线程调度是Java多线程的核心,只有良好的调度,才能充分发挥系统的性能
本文所述实例为VB读取内存、线程及句柄的一个API,对涉及系统底层操作的VB编程有一定的帮助,需要的读者可以参考使用。这个API可获取到线程ID,写内存,包括进