简体   繁体   中英

What is a daemon thread group in JAVA?

I know that a thread can be daemon or non-daemon. We can use isDaemon() method to check if thread is daemon or not. isDaemon() method also works on thread groups.

class MyThread extends Thread
{
 MyThread(ThreadGroup g, String name)
 {
  super(g,name);
 }
 public void run()
 {
  long i = 0;
  for(long l=0; l<999999999; l++)
  {
   i=i+3;
  }
 }
}

class Check
{
 public static void main(String[] args)
 {
  ThreadGroup sys = Thread.currentThread().getThreadGroup().getParent();
  ThreadGroup parent = new ThreadGroup("parent");
  MyThread t1 = new MyThread(parent, "t1");
  ThreadGroup child = new ThreadGroup(parent,"child");
  Thread t2 = new Thread(child, "t2");
  t1.start();
  t2.start();
  ThreadGroup[] t = new ThreadGroup[sys.activeGroupCount()];
  sys.enumerate(t);
  for(ThreadGroup ti: t)
  {
    System.out.println(ti.getName()+"  "+ti.isDaemon());
  }
    System.out.println(sys.getName()+"  "+sys.isDaemon());
}

Output:

main  false
parent  false
child  false
system  false

Here System is also a non-daemon thread group. How a thread group can be daemon? I mean what are the properties of a daemon thread group? How system thread-group is non-daemon?

The same way as Thread: java.lang.ThreadGroup#setDaemon . When you create a thread group you can mark it as daemon.

As per javadoc:

A daemon thread group is automatically destroyed when its last thread is stopped or its last thread group is destroyed.

Yes, you can set Thread group as daemon thread.

/**
 * Changes the daemon status of this thread group.
 * <p>
 * First, the <code>checkAccess</code> method of this thread group is
 * called with no arguments; this may result in a security exception.
 * <p>
 * A daemon thread group is automatically destroyed when its last
 * thread is stopped or its last thread group is destroyed.
 *
 * @param      daemon   if <code>true</code>, marks this thread group as
 *                      a daemon thread group; otherwise, marks this
 *                      thread group as normal.
 * @exception  SecurityException  if the current thread cannot modify
 *               this thread group.
 * @see        java.lang.SecurityException
 * @see        java.lang.ThreadGroup#checkAccess()
 * @since      JDK1.0
 */

Just like threads, Thread groups can also be daemon and non daemon. Daemon thread group does not mean that it will have all daemon threads in it.

A daemon thread group is a threadgroup that is automatically destroyed when its last thread is stopped or its last thread group is destroyed.

A non daemon thread group is not destroyed automatically even if there are no active threads in it or no child thread groups.

Consider this code :

We will be creating the following hierarchy of thread groups and each thread group will have the mentioned threads in it.

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

Code:

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());

    }
    
}

You will see that even though all threads in child thread groups of Main have died, still thread groups exist except the last one which we marked as daemon thread group.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM