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("=========守护线程结束执行=========");
}
}

可以看到,当主线程执行完毕后,非守护线程依旧在等待执行,直至非守护线程全部执行完毕后,程序才退出
守护线程时执行的情况
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("=========守护线程结束执行=========");
}
}

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