侧边栏壁纸
博主头像
此昵称不存在 博主等级

行动起来,活在当下

  • 累计撰写 35 篇文章
  • 累计创建 7 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

什么是守护线程(Daemon)

Administrator
2023-01-29 / 0 评论 / 0 点赞 / 384 阅读 / 0 字 / 正在检测是否收录...

Java线程默认为非守护线程,可通过Thread.currentThread().isDaemon()判断当前线程是否为守护线程
守护线程是程序运行时在后台提供服务的线程,并非系统中不可或缺的一部分
守护线程在其他非守护线程执行完毕后,自动终止,不会阻塞程序的结束,即 非守护线程执行完毕后,会立即杀死守护线程,不会再执行守护线程后续的代码逻辑

非守护线程时执行的情况

public class DaemonDemo {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().isDaemon());
        Thread thread = new Thread(new DaemonThread());
//        thread.setDaemon(true);
        thread.start();
        System.out.println(thread.isDaemon());
        System.out.println("主线程执行结束");
    }
}

class DaemonThread implements Runnable{


    @Override
    public void run() {
        System.out.println("=========守护线程开始执行=========");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("=========守护线程结束执行=========");
    }
}

image-1674998198000
可以看到,当主线程执行完毕后,非守护线程依旧在等待执行,直至非守护线程全部执行完毕后,程序才退出

守护线程时执行的情况

public class DaemonDemo {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().isDaemon());
        Thread thread = new Thread(new DaemonThread());
        thread.setDaemon(true);
        thread.start();
        System.out.println(thread.isDaemon());
        System.out.println("主线程执行结束");
    }
}

class DaemonThread implements Runnable{


    @Override
    public void run() {
        System.out.println("=========守护线程开始执行=========");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("=========守护线程结束执行=========");
    }
}

image-1674998358261
可以看出,当主线程执行完毕后,守护线程立马被终止了,后续代码不在执行,程序退出

0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区