守护线程¶
没有守护¶
public class TestDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("[守护线程]");
}
});
// thread.setDaemon(true); // true表示为守护线程
thread.start();
Thread.sleep(1000);
System.out.println("主线程退出");
}
}
[守护线程]
[守护线程]
[守护线程]
[守护线程]
[守护线程]
[守护线程]
[守护线程]
[守护线程]
[守护线程]
主线程退出
[守护线程]
[守护线程]
主线程结束 , 非守护线程不结束
守护线程¶
public class TestDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("[守护线程]");
}
});
thread.setDaemon(true);
thread.start();
Thread.sleep(1000);
System.out.println("主线程退出");
}
}
[守护线程]
[守护线程]
[守护线程]
[守护线程]
[守护线程]
[守护线程]
[守护线程]
[守护线程]
[守护线程]
主线程退出
主线程结束 , 守护线程结束