位置:首頁 > Java技術 > java.lang > java.lang.ThreadGroup.setDaemon()方法實例

java.lang.ThreadGroup.setDaemon()方法實例

java.lang.ThreadGroup.setDaemon() 方法改變該線程組的守護進程的狀態。當其最後一個線程被停止或它的最後一個線程組被銷毀守護線程組會自動銷毀。

聲明

以下是java.lang.ThreadGroup.setDaemon()方法的聲明

public final void setDaemon(boolean daemon)

參數

  • daemon -- 如果為true,這標誌著該線程組作為守護線程組;否則,標誌著該線程組為正常。

返回值

此方法不返回任何值。

異常

  • SecurityException -- 如果當前線程無法修改此線程組。

例子

下麵的例子顯示java.lang.ThreadGroup.setDaemon()方法的使用。

package com.yiibai;

import java.lang.*;

public class ThreadGroupDemo implements Runnable
{
   public static void main(String[] args) {
      ThreadGroupDemo tg = new ThreadGroupDemo();
      tg.func();
   }

   public void func() {
      try {     
         // create a parent ThreadGroup
         ThreadGroup pGroup = new ThreadGroup("Parent ThreadGroup");
         // daemon status is set to true
         pGroup.setDaemon(true);
    
         // create a child ThreadGroup for parent ThreadGroup
         ThreadGroup cGroup = new ThreadGroup(pGroup, "Child ThreadGroup");
         // daemon status is set to true
         cGroup.setDaemon(true);

         // create a thread
         Thread t1 = new Thread(pGroup, this);
         System.out.println("Starting " + t1.getName() + "...");
         t1.start();
            
         // create another thread
         Thread t2 = new Thread(cGroup, this);
         System.out.println("Starting " + t2.getName() + "...");
         t2.start();

         // returns true if this thread group is a daemon thread group
         System.out.println("Is " + pGroup.getName() + " a daemon
         ThreadGroup? " + pGroup.isDaemon());
         System.out.println("Is " + cGroup.getName() + " a daemon
         ThreadGroup? " + cGroup.isDaemon());

         // block until the other threads finish
         t1.join();
         t2.join();
      }
      catch (InterruptedException ex) {
         System.out.println(ex.toString());
      }
   }

   // implements run()
   public void run() {

      for(int i = 0;i < 1000;i++) {
         i++;
      }
      System.out.println(Thread.currentThread().getName() + 
      " finished executing.");
   }
}  

讓我們來編譯和運行上麵的程序,這將產生以下結果:

Starting Thread-0...
Starting Thread-1...
Is Parent ThreadGroup a daemonThreadGroup? true
Is Child ThreadGroup a daemonThreadGroup? true
Thread-0 finished executing.
Thread-1 finished executing.