前言
jdk 1.8
获取当前项目所有的线程
代码
import java.util.Random;
public class Test {
public static void main(String[] args) {
Test t = new Test();
t.initThreadContext();
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {}
t.printAllThread();
}
public void printAllThread(){
// 遍历线程组树,获取根线程组
ThreadGroup topGroup =Thread.currentThread().getThreadGroup();
while (topGroup.getParent()!=null){
// 返回此线程组的父线程组
topGroup=topGroup.getParent();
}
// 线程数组大小为当前活动线程数量的2倍。
Thread[] tmpThreadList = new Thread[topGroup.activeCount() * 2];
// 获取根线程组下的所有线程
int actualSize = topGroup.enumerate(tmpThreadList);
// 拷贝到一个新的数组,数组长度为实际长度
Thread[] threadList = new Thread[actualSize];
System.arraycopy(tmpThreadList, 0, threadList, 0, actualSize);
// 打印
for (Thread thread : threadList) {
System.out.println(" 线程id:" + thread.getId() + " 线程名称:" + thread.getName() + " 线程状态:" + thread.getState());
}
}
public void initThreadContext() {
for (int i=0; i<10; i++) {
Thread t = new Thread() {
public void run() {
Random random = new Random();
int times = random.nextInt(10) + 1;
System.out.println("thread " + this.getId() + " started, run " + times + " seconds");
for (int i=0; i<times; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
System.out.println("thread " + this.getId() + " done");
}
};
t.start();
}
}
}
执行结果
thread 10 started, run 8 seconds
thread 12 started, run 1 seconds
thread 11 started, run 3 seconds
thread 13 started, run 6 seconds
thread 14 started, run 1 seconds
thread 15 started, run 7 seconds
thread 17 started, run 7 seconds
thread 16 started, run 2 seconds
thread 18 started, run 2 seconds
thread 19 started, run 3 seconds
thread 12 done
thread 14 done
thread 18 done
thread 16 done
thread 19 done
thread 11 done
线程id:2 线程名称:Reference Handler 线程状态:WAITING
线程id:3 线程名称:Finalizer 线程状态:WAITING
线程id:4 线程名称:Signal Dispatcher 线程状态:RUNNABLE
线程id:5 线程名称:Attach Listener 线程状态:RUNNABLE
线程id:1 线程名称:main 线程状态:RUNNABLE
线程id:10 线程名称:Thread-0 线程状态:TIMED_WAITING
线程id:13 线程名称:Thread-3 线程状态:TIMED_WAITING
线程id:15 线程名称:Thread-5 线程状态:TIMED_WAITING
线程id:17 线程名称:Thread-7 线程状态:TIMED_WAITING
thread 13 done
thread 15 done
thread 17 done
thread 10 done