1、守护(Daemon)线程简介
守护线程是一中特殊的线程,就和它的名字一样,他是系统的守护者,在后台默默的完成一些系统性的服务,比如垃圾回收线程,JIT线程就可以理解为守护线程。与之对应的是用户线程。用户线程可以认为是系统的工作线程,它会完成这个程序应该要完成的业务操作。如果用户线程全部结束,这也就意味着这个程序实际上无事可做了。守护线程要守护的对象已经不存在了,那么整个应用程序就自然应该结束。
守护线程是一种支持型线程,因为它主要被用作程序中后台调度以及支持性工作。这就意味着,当一个Java虚拟机中不存在非Daemon线程的时候,Java虚拟机将会退出。可以通过调用Thread.setDaemon(true)将线程设置为Deamon线程。 Daemon属性需要在线程启动前设置,不能在线程启动后设置。
2、Daemon线程的例子
public class DeamonDemo {
public static class DaemonThread extends Thread {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
System.out.println("I am alive ...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
// 守护线程
Thread thread = new DaemonThread();
thread.setDaemon(true);
thread.start();
// 程序要运行的任务
Thread.sleep(3100);
}
}
注意: Daemon属性需要在线程启动前设置,不能在线程启动后设置。
3、在Java虚拟机退出的时候,Daemon线程的finally块不一定会执行
public class Daemon {
public static void main(String[] args) {
Thread thread = new Thread(new DaemonRunner(), "DaemonRunner");
thread.setDaemon(true);
thread.start();
}
static class DaemonRunner implements Runnable {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("DaemonThread finally run.");
}
}
}
}
注意: 在构建Deamon线程时,不能依靠finally块中的内容来确保执行关闭或者清理资源的逻辑。
4、参考资料
Java并发编程的艺术
Java高并发程序设计