?? listallrunningthread.java
字號(hào):
package book.thread;
public class ListAllRunningThread {
/**
* 列出所有線程的信息
*/
public static void list(){
//獲取當(dāng)前線程所屬線程組的父線程組
ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
//不斷循環(huán),直到找到根線程組
while (root.getParent() != null) {
root = root.getParent();
}
//訪問(wèn)根線程組下的線程
visit(root, 0);
}
/**
* 遞歸的顯示線程組中的線程
* @param group
* @param level
*/
private static void visit(ThreadGroup group, int level) {
// 獲取group線程組中活動(dòng)線程的估計(jì)數(shù)
int numThreads = group.activeCount();
Thread[] threads = new Thread[numThreads];
// 把此線程組中的所有活動(dòng)線程復(fù)制到指定數(shù)組中。
// false表示不包括作為此線程組的子組的線程組中的線程。
numThreads = group.enumerate(threads, false);
// 遍歷活動(dòng)線程數(shù)組,打印它們的名字
for (int i=0; i<numThreads; i++) {
// Get thread
Thread thread = threads[i];
for (int j=0; j<level; j++){
System.out.print(" ");
}
System.out.println("" + thread.getName());
}
// 獲取group線程組中活動(dòng)子線程組的估計(jì)數(shù)
int numGroups = group.activeGroupCount();
ThreadGroup[] groups = new ThreadGroup[numGroups];
// 把對(duì)此線程組中的所有活動(dòng)子組的引用復(fù)制到指定數(shù)組中。
numGroups = group.enumerate(groups, false);
// 遞歸的訪問(wèn)子線程組中的線程
for (int i=0; i<numGroups; i++) {
visit(groups[i], level+1);
}
}
/**
* @param args
*/
public static void main(String[] args) {
//建立一個(gè)線程組
ThreadGroup group1 = new ThreadGroup("ThreadGroup-1");
//建立3個(gè)線程并啟動(dòng)
Thread[] threads1 = new Thread[3];
for (int i=1; i<4; i++){
//新的線程屬于group1線程組,以ThreadA為運(yùn)行對(duì)象,名字為"group1-ThreadA-i"
threads1[i-1] = new Thread(group1, new ThreadA(i*2000), "group1-ThreadA-" + i);
threads1[i-1].start();
}
//建立另一個(gè)線程組,屬于group1線程組
ThreadGroup group2 = new ThreadGroup(group1, "ThreadGroup-2");
//建立3個(gè)線程并啟動(dòng)
Thread[] threads2 = new Thread[3];
for (int i=1; i<4; i++){
//新的線程屬于group2線程組,以ThreadA為運(yùn)行對(duì)象,名字為"group2-ThreadA-i"
threads2[i-1] = new Thread(group2, new ThreadA(i*1000), "group2-ThreadA-" + i);
threads2[i-1].start();
}
//列出所有活動(dòng)的線程的名字
System.out.println("當(dāng)前虛擬機(jī)中所有正在運(yùn)行的線程:");
ListAllRunningThread.list();
}
static class ThreadA extends Thread{
private long sleepTime = 100;
public ThreadA(long time){
this.sleepTime = time;
}
public void run(){
try {
Thread.sleep(this.sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -