![Java多线程编程核心技术(第3版)](https://wfqqreader-1252317822.image.myqcloud.com/cover/745/42637745/b_42637745.jpg)
上QQ阅读APP看书,第一时间看更新
1.10 方法getId()
getId()方法可以取得线程的唯一数字标识。
创建测试项目runThread,创建Test.java类,代码如下:
package test1; public class Test { public static void main(String[] args) { Thread runThread = Thread.currentThread(); System.out.println(runThread.getName() + " " + runThread.getId()); Thread t1 = new Thread(); System.out.println(t1.getName() + " " + t1.getId()); Thread t2 = new Thread(); System.out.println(t2.getName() + " " + t2.getId()); Thread t3 = new Thread(); System.out.println(t3.getName() + " " + t3.getId()); Thread t4 = new Thread(); System.out.println(t4.getName() + " " + t4.getId()); Thread t5 = new Thread(); System.out.println(t5.getName() + " " + t5.getId()); } }
![](https://epubservercos.yuewen.com/204B22/22139293909121606/epubprivate/OEBPS/Images/1-36.jpg?sign=1739133372-q0Xj7KYkqKmFditqaHdb9AWZDYfbaZsU-0-a90551e4aae65526b4fc8ac8314807bb)
图1-36 获取线程名称及id值
程序运行结果如图1-36所示。
从运行结果来看,当前执行代码的线程名为main,线程id值为1。
而Thread-0线程的id值直接到达11,说明中间有9个id值被隐藏的线程占有。