- Java多线程编程核心技术(第3版)
- 高洪岩
- 200字
- 2022-01-07 14:44:02
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()); } }

图1-36 获取线程名称及id值
程序运行结果如图1-36所示。
从运行结果来看,当前执行代码的线程名为main,线程id值为1。
而Thread-0线程的id值直接到达11,说明中间有9个id值被隐藏的线程占有。