在Java程式設計中,如何顯示所有正在執行的執行緒?
以下範例演示如何使用getName()
方法顯示所有正在執行的執行緒的名稱。
package com.yiibai;
public class DisplayRunningThread extends Thread {
public static void main(String[] args) {
DisplayRunningThread t1 = new DisplayRunningThread();
t1.setName("thread1");
t1.start();
DisplayRunningThread t2 = new DisplayRunningThread();
t2.setName("thread2");
t2.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
Thread No:2 = thread2