Java setDaemon()方法
 
 
 线程类的setDaemon()方法用于将线程标记为守护线程或用户线程。它的寿命取决于用户线程,即所有用户线程死亡时,JVM会自动终止该线程。必须在线程启动之前调用它。
 
 如果在声明线程之后调用setDaemon()方法,则此方法将引发
  IllegalThreadStateException 。
 
语法
 
 
  
   public final void setDaemon(boolean on)
  
 
 
  
参数
 
 
 开启: 如果为true,则将该线程标记为守护程序线程。
 
返回
 
 如果线程是守护程序线程,则此方法将返回true,否则返回false。 
 
异常
 
 
  IllegalThreadStateException: 如果线程处于活动状态。
 
 
  SecurityException: 如果当前线程无法修改该线程。
 
示例1 
 
 
  
   public class JavaSetDaemonExp1 extends Thread
 {
     public void run()
     {
         //checking for daemon thread 
         if(Thread.currentThread().isDaemon())
         {
             System.out.println("daemon thread work");
         }
         else
         {
             System.out.println("user thread work");
         }
     }
     public static void main(String[] args)
     {
         // creating three threads
         JavaSetDaemonExp1 t1=new JavaSetDaemonExp1();
         JavaSetDaemonExp1 t2=new JavaSetDaemonExp1();
         JavaSetDaemonExp1 t3=new JavaSetDaemonExp1();
         // set user thread t1 to daemon thread 
         t1.setDaemon(true);
         //call run() method
         t1.start();
         // set user thread t2 to daemon thread 
         t2.setDaemon(true);
         // start of threads 
         t2.start();
         t3.start();
     }
 }
  
 
 
  
 
 输出:  
 
 
  
   daemon thread work
 daemon thread work
 user thread work
  
 
 
  
示例2 
 
 在线程启动后调用setDaemon()方法时。
 
 
  
   public class JavaSetDaemonExp2 extends Thread
 {
     public void run()
     {
         System.out.println("Name of thread: "+Thread.currentThread().getName());
         //
         //checking for daemon thread 
         System.out.println("Daemon: "+Thread.currentThread().isDaemon());
     }
     public static void main(String[] args)
     {
         // creating two threads 
         JavaSetDaemonExp2 t1=new JavaSetDaemonExp2();
         JavaSetDaemonExp2 t2=new JavaSetDaemonExp2();
         // call run() method 
         t1.start();
         // this will throw exception here 
         t1.setDaemon(true);
         // call run() method 
         t2.start();
     }
 }
  
 
 
  
 
 输出:  
 
 
  
   Name of thread: Thread-0
 Daemon: false
 Exception in thread "main" java.lang.IllegalThreadStateException
 at java.lang.Thread.setDaemon(Thread.java:1359)
 at JavaSetDaemonExp2.main(JavaSetDaemonExp2.java:17)