Java 实例 - 获取线程id
Java 教程
· 2019-02-12 06:14:21
以下实例演示了如何使用 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
点击查看所有 Java 教程 文章: https://www.codercto.com/courses/l/12.html
JavaScript开发王
张亚飞 / 2008-6 / 65.00元
《网站开发专家·JavaScript开发王》详细介绍使用JavaScript脚本开发应用程序,并融合在网页中实现动态网页,内容也包含DHTML和AJAX。这《网站开发专家·JavaScript开发王》有严格的逻辑性,不论是JavaScript语言、DHTML,还是AJAX,《网站开发专家·JavaScript开发王》首先帮助用户建立首要的、基础的正确认知,然后通过实例,说明如何利用JavaScri......一起来看看 《JavaScript开发王》 这本书的介绍吧!
Base64 编码/解码
Base64 编码/解码
正则表达式在线测试
正则表达式在线测试