在启动线程前调用setDaemon()方法,该线程就会变成一个后台线程,当所有前台线程执行完毕,整个进程就会结束,JVM也会通知后台进程结束。(垃圾回收机制)
public class X10_6 {
public static void main(String[] args) { //后台线程
if (Thread.currentThread().isDaemon()) {
System.out.println("main线程是后台线程");
} else System.out.println("main线程不是后台线程");
Thread t1 = new Thread(() -> {
while (true) {
System.out.println(Thread.currentThread().getName() + "在运行");
}
}, "t1线程");
System.out.println("t1线程的默认是"+((t1.isDaemon()) ? "后台线程":"前台线程"));
t1.setDaemon(true);
System.out.println("t1线程被设置为"+((t1.isDaemon()) ? "后台线程":"前台线程"));
t1.start();
for (int i = 0; i < 50; i++) {
System.out.println(i);
}
}
}
在守护线程中产生的新线程也是守护的
public static void main(String[] args) throws InterruptedException{
Thread t = new Thread(() -> {
Thread it = new Thread(() -> {
while (true){
try {
System.out.println("程序正常运行中...");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
it.start();
});
t.setDaemon(true); //设置为守护线程(必须在开始之前,中途是不允许转换的)
t.start();
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
}
}