Skip to content

守护线程(Daemon Thread)

  • 守护线程是一种特殊的线程,它的作用是为其他线程提供服务。
  • 守护线程的特点是当所有的非守护线程结束后,守护线程会自动销毁。
  • 守护线程的生命周期是由JVM自己的线程调度器进行管理,不需要用户手动管理。
  • 守护线程的优先级比较低,通常情况下,守护线程不会影响其他线程的执行。
  • 守护线程的创建方式是通过Thread.setDaemon(true)方法设置。
  • 守护线程的使用范围很广,例如垃圾回收线程、JIT编译线程,监听,事务等都是守护线程。
  • 守护线程的使用示例如下:
java
public class DaemonThreadDemo {
    public static void main(String[] args) {
        Thread daemonThread = new Thread(() -> {
            while (true) {
                System.out.println("Daemon thread begin!");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("Daemon thread end!");
            }
        });
        daemonThread.setDaemon(true);
        daemonThread.start();
        System.out.println("Hello from main thread!");
    }
}