Java 示例 - 显示所有正在运行的线程?
-
问题描述
如何显示所有正在运行的线程? -
解决方案
以下示例演示如何使用 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()); } }
-
结果
上面的代码示例将产生以下结果。Thread No:0 = main Thread No:1 = thread1