Deamon线程通常是一种在后台提供通用服务的线程,当程序中的非后台线程全部终止时,deamon线程也就终止了。
setDaemon(boolean isDaemon)
方法的一段注释:
The Java Virtual Machine exits when the only threads running are all daemon threads.
意思就是当运行中的线程只剩下守护线程时,jvm将会退出。
下面看一个守护线程的实例:
public class DaemonTest {
public static void main(String[] args) throws Exception {
//启动10个daemon线程
for (int i = 0;i < 10;i ++) {
Thread thread = new Thread(new DaemonTask());
thread.setDaemon(true);
thread.start();
}
System.out.println("All Daemon Thread have been started.");
TimeUnit.SECONDS.sleep(3);
System.out.println("Main Thread has completed.");
}
}
class DaemonTask implements Runnable {
@Override
public void run() {
try{
while (!Thread.interrupted()) {
System.out.println("Daemon thread is running...");
TimeUnit.SECONDS.sleep(1);
}
}catch (Exception ex) {
ex.printStackTrace();
}finally {
System.out.println(Thread.currentThread().getName() + " : Daeming finally block.");
}
}
}
当主线程运行完成时,所有daemon线程都会立即终止。
需要注意的是,daemon线程被终止时,既不会抛出异常,也不执行finally语句块,所以,不应该在daemon线程中进行资源释放的操作,因为没有办法保证一定被执行。