Java中的用户线程与守护程序线程?

 守护线程 通常用来为用户线程执行服务。应用程序线程的main()方法用户线程(非守护线程)。在JVM不会终止,除非所有的用户线程(非守护)终止。我们可以通过调用setDaemon(true)将由 用户线程创建的线程明确指定为守护程序线程。通过使用方法isDaemon()确定线程是否是守护程序线程。

示例

public class UserDaemonThreadTest extends Thread {
   public static void main(String args[]) {
      System.out.println("Thread name is : "+ Thread.currentThread().getName());      // Check whether the main thread is daemon or user thread      System.out.println("Is main thread daemon ? : "+ Thread.currentThread().isDaemon());
      UserDaemonThreadTest t1 = new UserDaemonThreadTest();
      UserDaemonThreadTest t2 = new UserDaemonThreadTest();
      // Converting t1(user thread) to a daemon thread
      t1.setDaemon(true);
      t1.start();
      t2.start();
   }
   public void run() {
      //检查线程是否是守护进程
      if (Thread.currentThread().isDaemon()) {
         System.out.println(Thread.currentThread().getName()+" is a Daemon Thread");
      } else {
         System.out.println(Thread.currentThread().getName()+" is an User Thread");
      }
   }
}

输出结果

Thread name is : main
Is main thread daemon ? : false
Thread-0 is a Daemon Thread
Thread-1 is an User Thread