Thread类中有一个属性daemon,表示线程是否是守护线程,默认值是false。与守护线程对应的是用户线程;
用户线程:daemon=false,有任务就执行。
守护线程:daemon=true,如果有用户线程存活就执行任务,如果没有用户线程存活,就退出;
二、用户线程示例 public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().isDaemon());
while (true){
}
});
thread.start();
Thread main = Thread.currentThread();
System.out.println(main.getName());
System.out.println(main.isDaemon());
}
thread线程是用户线程,while是一个死循环,程序始终处于运行状态。
31行使用断点,查看thread和main线程的参数,均为用户线程
三、守护线程
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().isDaemon());
while (true){
}
});
thread.setDaemon(true);
thread.start();
Thread main = Thread.currentThread();
System.out.println(main.getName());
System.out.println(main.isDaemon());
}
thread线程是守护线程,虽然while是一个死循环,当用户线程main运行结束,thread随即终止。
32打断点,dubeg运行
线程setDaemon()设置必须在线程执行前运行,否则会报java.lang.IllegalThreadStateException异常。



