守护线程
守护线程
线程分为用户线程和守护线程
-
虚拟机必须确保用户线程的结束
-
虚拟机不必等待守护线程的结束
-
垃圾回收,监控回收等就是一个守护线程。(相当于学校的门卫,他必须确保学校里面没人了才会关门)
-
thread.setDaemon(true);//默认为false代表用户线程,true为守护线程
public class Daemon {
public static void main(String[] args) {
You you = new You();
God god = new God();
Thread thread = new Thread(god);
thread.setDaemon(true);////默认为false代表用户线程,true为守护线程
thread.start();
new Thread(you).start();
}
}
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 365; i++) {
System.out.println("开心的过每一天");
}
System.out.println("一年结束了,很开心");
}
}
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("上帝保佑你");
}
}
}