如何显示所有正在运行的线程?(How to display all running Thread?)
优质
小牛编辑
123浏览
2023-12-01
问题描述 (Problem Description)
如何显示所有正在运行的线程?
解决方案 (Solution)
以下示例演示如何使用getName()方法显示所有正在运行的线程的名称。
public class Main extends Thread {
public static void main(String[] args) {
Main t1 = new Main();
t1.setName("thread1");
t1.start();
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
int noThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[noThreads];
currentGroup.enumerate(lstThreads);
for (int i = 0; i < noThreads; i++) System.out.println("Thread No:" + i + " = " + lstThreads[i].getName());
}
}
结果 (Result)
上面的代码示例将产生以下结果。
Thread No:0 = main
Thread No:1 = thread1