守护线程
-
线程可以分为用户线程和守护线程
-
虚拟机必须确保用户线程执行完毕,比如main()主线程
-
虚拟机不用等待守护线程执行完毕,比如gc()垃圾回收线程
-
采用Thread.setDaemon(bool)方法设置守护线程,默认为false
例子
package MultiProcess;
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
Me me = new Me();
Thread godThread = new Thread(god);
Thread meThread = new Thread(me);
godThread.setDaemon(true);
godThread.start();
meThread.start();
}
}
class God implements Runnable{
@Override
public void run() {
while (true)
System.out.println("上帝守护着你");
}
}
class Me implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("开心的过第"+ (i+1) + "天");
}
System.out.println("GG");
}
}
结果
上帝守护着你
上帝守护着你
开心的过第36497天
开心的过第36498天
开心的过第36499天
开心的过第36500天
GG
上帝守护着你
上帝守护着你
上帝守护着你
用户线程结束后,守护线程运行了一会,虚拟机停止。