守护线程: 为程序提供后端服务的线程成为守护线程,非守护线程运行结束时守护线程也一并结束;

用户线程:用户线程和守护线程唯一的区别就是Daemon(Thread.getDaemon())为false;

下面简单演示一些守护线程跟非守护线程执行情况:

public static void main(String[] args) {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                System.out.println("守护线程开始执行...");
                while(true){
                    System.out.println("守护线程休眠中..");
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });
    thread.setDaemon(true);
    thread.start();
    try {
        System.out.println(Thread.currentThread().getName() + "线程已休眠..");
        Thread.sleep(5000);
        System.out.println(Thread.currentThread().getName() + "线程休眠结束..");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

守护线程和用户线程的区别

从打印信息上可以看出我们设置的守护线程为while(true)每隔一秒打印一次信息,main线程休眠5秒后结束,main线程结束时jvm直接停止了;

相关文章:

  • 2022-12-23
  • 2022-02-16
  • 2022-12-23
  • 2021-11-19
  • 2022-12-23
  • 2021-06-17
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-10
  • 2021-07-21
  • 2021-10-19
  • 2022-02-01
  • 2022-02-16
  • 2021-11-13
  • 2022-12-23
相关资源
相似解决方案