Java 實(shí)例 - 獲取所有線程
以下實(shí)例演示了如何使用 getName() 方法獲取所有正在運(yùn)行的線程:
/* author by w3cschool.cn Main.java */ 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("線程號(hào):" + i + " = " + lstThreads[i].getName()); } }
以上代碼運(yùn)行輸出結(jié)果為:
線程號(hào):0 = main 線程號(hào):1 = thread1
更多建議: