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

javaobject oriented programmingprogramming更新于 2024/7/25 20:34:00

 守护线程 通常用于为用户线程执行服务。应用程序线程的 ma​​in() 方法用户线程(非守护线程)。除非所有 用户线程(非守护线程) 终止,否则 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

相关文章