ThreadGroup
類的enumerate()
方法用於將每個活動線程的線程組及其子組複製到指定的數組中。 此方法使用tarray
參數調用`enumerate()方法。
語法
public int enumerate(Thread[] tarray)
參數
tarray
:它是要複製到的Thread
對象數組。
返回
此方法返回放入數組的線程數。
package com.zaixian.threadgroup;
class NewThread extends Thread {
NewThread(String threadname, ThreadGroup tg) {
super(tg, threadname);
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
System.out.println(Thread.currentThread().getName() + " interrupted");
}
}
System.out.println(Thread.currentThread().getName() + " completed executing");
}
}
public class ThreadGroupEnumerateExp {
public static void main(String arg[]) {
// creating the ThreadGroup
ThreadGroup g1 = new ThreadGroup("Parent thread");
// creating a child ThreadGroup for parent ThreadGroup
ThreadGroup g2 = new ThreadGroup(g1, "child thread");
// creating a thread
NewThread t1 = new NewThread("Thread-1", g1);
System.out.println("Starting of Thread-1");
t1.start();
// creating another thread
NewThread t2 = new NewThread("Thread-2", g1);
System.out.println("Starting of Thread-2");
t2.start();
// returns the number of threads put into the array
Thread[] tarray = new Thread[g1.activeCount()];
int count = g1.enumerate(tarray);
// prints active threads
for (int i = 0; i < count; i++)
System.out.println(tarray[i].getName() + " found");
}
}
執行上面示例代碼,得到以下結果:
Starting of Thread-1
Starting of Thread-2
Thread-1 found
Thread-2 found
Thread-1 completed executing
Thread-2 completed executing
上一篇:
Java線程組
下一篇:
Java關閉掛鉤(shutdown hook)