Java获取线程ID的实例

网友投稿 308 2022-11-18


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 =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的资料请关注我们其它相关文章!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java如何读取配置文件并赋值静态变量
下一篇:java8 stream sort自定义复杂排序案例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~