就像线程一样,线程组也可以是守护进程和非守护进程。守护线程组并不意味着它将拥有所有守护线程。
守护线程组是在其最后一个线程停止或其最后一个线程组被销毁时自动销毁的线程组。
即使其中没有活动线程或没有子线程组,非守护线程组也不会自动销毁。
考虑这段代码:
我们将创建以下线程组层次结构,每个线程组中都会有提到的线程。
Main Threadgroup - 2 threads: one main , one thread-1
|
child Threadgroup - 1 thread: thread-2
|
child child Threadgroup - 1 thread: thread-3
|
child child child Threadgroup (daemon thread group) - 1 thread : thread-4
代码:
class CustomRunnable implements Runnable {
@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(Thread.currentThread().getThreadGroup(), new CustomRunnable(), "Thread-1");
ThreadGroup childOfMainThreadGroup = new ThreadGroup("childOfMainThreadGroup");
Thread t2 = new Thread(childOfMainThreadGroup, new CustomRunnable(), "Thread-2");
ThreadGroup childChildOfMainThreadGroup = new ThreadGroup(childOfMainThreadGroup, "childChildOfMainThreadGroup");
Thread t3 = new Thread(childChildOfMainThreadGroup, new CustomRunnable(), "Thread-3");
// We will create a daemon thread group
ThreadGroup childChildChildOfMainThreadGroup = new ThreadGroup(childChildOfMainThreadGroup, "childChildChildOfMainThreadGroup");
childChildChildOfMainThreadGroup.setDaemon(true);
// This is non daemon thread in it
Thread t4 = new Thread(childChildChildOfMainThreadGroup, new CustomRunnable(), "Thread-4");
t1.start();
t2.start();
t3.start();
t4.start();
Thread.currentThread().getThreadGroup().list();
System.out.println(Thread.currentThread().getThreadGroup().activeCount());
System.out.println(Thread.currentThread().getThreadGroup().activeGroupCount());
// Main thread waits for all threads to complete
t1.join();
t2.join();
t3.join();
t4.join();
System.out.println("-----------------");
Thread.currentThread().getThreadGroup().list();
System.out.println(Thread.currentThread().getThreadGroup().activeCount());
System.out.println(Thread.currentThread().getThreadGroup().activeGroupCount());
}
}
您会看到,即使 Main 的子线程组中的所有线程都已死亡,除了我们标记为守护线程组的最后一个线程组之外,仍然存在线程组。