Java如何获取正在运行的线程的Id

2024-10-22 15:33:15
推荐回答(2个)
回答1:

使用:Thread.currentThread().getName() 就可以了

比如会输出:pool-1-thread-7

回答2:

public class  线程id

{

public static void main(String[] args) 

{

System.out.println("\n\t\t==========多线程怎么查看当前线程id==========\n");

init();

}//初始化!

private static void init()

{

for (int i=0;i<2 ;i++ )

{

new Thread(new TestRunnable()).start();

}

}

}

class TestRunnable implements Runnable

{

//简单测试直接用了静态,偷懒了!

private static int i=10;

public void run()

{

show();

}

synchronized void show()

{

while(i>=1)

System.out.println("当前执行的线程Id是:"+Thread.currentThread().getName()+"---->"+i--+"\n");

}

}