getThreadGroup() 获取当前线程组
Thread.activeCount() 获取线程数量-是个估计值(因为线程的状态随时可能变化)
threadGroup.enumerate(threads) 复制threadGroup中的线程到threads数组里面,然后就可以操作threads了
/**
* getThreadGroup()获取当前线程组
* Thread.activeCount()获取线程数量-是个估计值(因为线程的状态随时在变化)
* threadGroup.enumerate(threads) // 复制threadGroup中的线程到threads数组里面
*/
public class ThreadGroupDemo implements Runnable{
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(new ThreadGroupDemo()).start();
}
ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); // 当前threadGroup
Thread[] threads = new Thread[Thread.activeCount()]; // 线程数组-用来存放线程
threadGroup.enumerate(threads); // 复制threadGroup中的线程到线程数组里面
for (int i = 0; i < Thread.activeCount(); i++){
System.out.println(threads[i].getName());
}
}
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}