什么是JAVA中的守护程序线程组?

时间:2016-05-25 08:41:38

标签: java multithreading threadgroup

我知道线程可以是守护进程或非守护进程。我们可以使用isDaemon()方法来检查线程是否是守护进程。 isDaemon()方法也适用于线程组。

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

输出:

main  false
parent  false
child  false
system  false

此处System也是非守护程序线程组。线程组如何成为守护进程?我的意思是守护程序线程组的属性是什么?系统线程组是如何非守护进程的?

2 个答案:

答案 0 :(得分:3)

与线程相同:java.lang.ThreadGroup#setDaemon。创建线程组时,可以将其标记为守护程序。

根据javadoc:

  

守护程序线程组在其最后一个线程时自动销毁   停止或其最后一个线程组被销毁。

答案 1 :(得分:1)

是的,您可以将Thread group设置为守护程序线程。

/**
 * 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
 */