4

スレッドがデーモンまたは非デーモンになる可能性があることを知っています。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 も非デーモン スレッド グループです。スレッドグループがどのようにデーモンになることができますか? デーモン スレッド グループのプロパティとは何ですか? システムスレッドグループが非デーモンである理由は?

4

3 に答える 3

4

スレッドと同じ方法: java.lang.ThreadGroup#setDaemon. スレッド グループを作成すると、それをデーモンとしてマークできます。

javadocに従って:

最後のスレッドが停止するか、最後のスレッド グループが破棄されると、デーモン スレッド グループは自動的に破棄されます。

于 2016-05-25T09:06:02.957 に答える
1

はい、スレッドグループをデーモンスレッドとして設定できます。

/**
 * 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
 */
于 2016-05-25T09:10:47.857 に答える