1. daemon线程即守护线程
Java 中有两种线程: 一种是用户线程(User Thread),一种是守护线程(Daemon Thread)。
守护线程是一种特殊的线程, 它的特殊有“陪伴”的含义, 当线程中不存在非守护线程时, 则守护线程自动销毁。
垃圾回收线程就是一种守护线程, 当线程中没有非守护线程了, 则垃圾回收线程就会自动销毁。
因此, 守护线程的作用就是为其他非守护线程的线程服务, 当非守护线程不存在时, 其自然就没有存在的必要了。
当一个JVM中所有非daemon线程都退出了,JVM就会退出。
2. 标志是否是daemon线程
setDaemon(boolean);必须在线程启动之前(start()方法前)进行设置。
boolean isDaemon();判断是否是守护线程
注意:守护线程中产生的线程也是守护线程;
例1:setDaemon(true)
import java.util.concurrent.TimeUnit;
public class DaemonTest {
public static void main(String[] args) {
Thread thread = new Thread(new DaemonRunner(),"DaemonRunner");
thread.setDaemon(true);//start方法前
thread.start();
}
static class DaemonRunner implements Runnable{
@Override
public void run() {
try{
TimeUnit.SECONDS.sleep(10);
}catch (InterruptedException e){
System.out.println("Setp into InterruptedException.");
} finally {
System.out.println("DaemonThread finally run.");
}
}
}
}
分析:运行代码控制台输出为空,为何?
程序运行,main线程中启动了Daemon线程,然后main线程马上就结束了,此时JVM中已经没有非Daemon线程了,所以JVM退出了。JVM中的所有Daemon线程也都需要立即终止,即使finally块中的内容还没有打印,DaemonRunner线程也终止了。
构建Daemon线程时,不能依靠finally块中的内容确保执行关闭或者清理资源的逻辑。
例2:setDaemon(false)
public class DaemonTest {
public static void main(String[] args) {
WorkerThread thread = new WorkerThread();
System.out.printf("work thread daemon: %b\n", thread.isDaemon());
System.out.printf("main thread daemon: %b\n", Thread.currentThread().isDaemon());
thread.start();
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main thread exit") ;
//System.exit(0);
}
}
class WorkerThread extends Thread {
public WorkerThread() {
// if true, JVM will quit after main thread quit
// if false, JVM will not quit, because this workerThread will never end.
setDaemon(false);
}
public void run() {
for (int i = 0; ; i++) {
System.out.printf("work thread loop: %d\n", i);
try {
sleep(1 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
运行结果:JVM将不会退出了
work thread daemon: false
main thread daemon: false
work thread loop: 0
work thread loop: 1
work thread loop: 2
main thread exit
work thread loop: 3
work thread loop: 4
......