守护线程: 为程序提供后端服务的线程成为守护线程,非守护线程运行结束时守护线程也一并结束;
用户线程:用户线程和守护线程唯一的区别就是Daemon(Thread.getDaemon())为false;
下面简单演示一些守护线程跟非守护线程执行情况:
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("守护线程开始执行...");
while(true){
System.out.println("守护线程休眠中..");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.setDaemon(true);
thread.start();
try {
System.out.println(Thread.currentThread().getName() + "线程已休眠..");
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() + "线程休眠结束..");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
从打印信息上可以看出我们设置的守护线程为while(true)每隔一秒打印一次信息,main线程休眠5秒后结束,main线程结束时jvm直接停止了;