- Java 教程
- Java 简介
- Java 开发环境配置
- Java 基础语法
- Java 对象和类
- Java 基本数据类型
- Java 变量类型
- Java 修饰符
- Java 运算符
- Java 循环结构 - for, while 及 do...while
- Java 分支结构 - if...else/switch
- Java Number & Math 类
- Java Character 类
- Java String 类
- Java StringBuffer 和 StringBuilder 类
- Java 数组
- Java 日期时间
- Java 正则表达式
- Java 方法
- Java 流(Stream)、文件(File)和IO
- Java Scanner 类
- Java 异常处理
- Java URL处理
- 安装Java环境(Linux)
- Java 面向对象
- Java 高级教程
- Java 8 新特性
Java 实例 - 获取线程id
以下实例演示了如何使用 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 实例 - 线程挂起
分类导航
- Java教程
- Vim教程
- Swing教程
- Spring教程
- Spring Web Services教程
- Spring MVC教程
- Spring JDBC教程
- Spring Cloud教程
- Spring Boot教程
- Spring Boot CLI教程
- Spring Batch教程
- Spring AOP教程
- PDFBox教程
- JSP教程
- JSF教程
- JPA教程
- Java面向对象设计
- Java设计模式
- Java虚拟机教程
- Java泛型教程
- Java正则表达式教程
- Java数据类型教程
- Java并发编程教程
- Java密码学教程
- Java多线程教程
- Java国际化(i18n)教程
- JavaFX教程
- Java9教程
关注微信小程序
扫描二维码
程序员编程王