官方解释
public class ThreadGroup extends Object implements Thread.UncaughtExceptionHandler
A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent.
当在main方法中未指定一个线程的名字和对应的线程组的名称时,jvm会自动创建一个main线程,该线程组的名称也为main
System.out.println(Thread.currentThread().getName());//main
System.out.println(Thread.currentThread().getThreadGroup().getName());//main
一个线程组可以成为另一个线程组的父线程组
ThreadGroup tg1 = new ThreadGroup("TG1"); Thread t1 = new Thread(tg1, "t1") { @Override public void run() { try { //TG1 System.out.println(getThreadGroup().getName()); //java.lang.ThreadGroup[name=main,maxpri=10] System.out.println(getThreadGroup().getParent()); System.out.println(getThreadGroup().getParent().activeCount()); Thread.sleep(10_000); } catch (InterruptedException e) { e.printStackTrace(); } } }; t1.start(); ThreadGroup tg2 = new ThreadGroup(tg1, "TG2"); //TG2 System.out.println(tg2.getName()); //java.lang.ThreadGroup[name=TG1,maxpri=10] System.out.println(tg2.getParent());
线程组.activeCount()可以获取当前线程组以及子线程组此时活着的线程
ThreadGroup tg1 = new ThreadGroup("TG1"); Thread t1 = new Thread(tg1, "t1") { @Override public void run() { try { Thread.sleep(10_000); } catch (InterruptedException e) { e.printStackTrace(); } } }; t1.start(); ThreadGroup tg2 = new ThreadGroup(tg1, "TG2"); Thread t2 = new Thread(tg2, "t2") { @Override public void run() { //TG1 System.out.println(tg1.getName()); Thread[] threads = new Thread[tg1.activeCount()]; tg1.enumerate(threads); //Thread[t1,5,TG1] //Thread[t2,5,TG2] Arrays.asList(threads).forEach(System.out::println); } }; t2.start();