十九、守护线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕,如main()线程
- 虚拟机不用等待守护线程执行完毕,如后台记录操作日志,监控内存,垃圾回收:gc()等。
public class ThreadDaemon {
public static void main(String[] args) {
You you = new You();
God god = new God();
Thread yt = new Thread(you);
Thread gt = new Thread(god);
//false:用户线程 true守护线程
yt.setDaemon(false);
gt.setDaemon(true);
yt.start();
gt.start();
}
}
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("God is watching over you");
}
}
}
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("Live happily");
}
System.out.println("GoodBye World!");
}
}
结果: