用户线程和守护线程
Stackoverflow中关于守护线程有如下比较好的解释:
Daemon threads are like assistants. Non-Daemon i.e. user threads are like front performers. Assistants help performers to complete a job. When the job is completed, no help is needed by performers to perform anymore. As no help is needed the assistants leave the place. So when the jobs of Non-Daemon threads is over, Daemon threads march away.
使用守护线程的目的
- 守护线程(Daemon Thread)是一个后台(background)线程,它用来辅助用户线程。
- 守护线程通常用来执行一些后台任务,比如说垃圾回收。
关于守护线程的一些重要点
- 守护线程通常都是低优先级执行
- 守护线程的生命周期依赖于用户线程
- 守护进程线程是在同一进程中运行的用户线程的服务提供者
- 如果非守护进程线程正在执行,Java VM就不会退出
- 如果只执行守护进程线程,Java VM将退出
使用守护线程
案例一
public class DaemonThread {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " running");
Thread.sleep(10000);
System.out.println(Thread.currentThread().getName() + " done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.setDaemon(true);
// runnable -> running|dead|blocked
t.start();
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName());
}
}
执行结果:main线程执行结束后,t线程就会停止。
案例二
public class DaemonThread1 {
public static void main(String[] args) {
Thread t = new Thread() {
@Override
public void run() {
Thread innerThread = new Thread() {
@Override
public void run() {
try {
while(true) {
System.out.println("Do something for health check.");
Thread.sleep(10000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
innerThread.setDaemon(true);
innerThread.start();
try {
Thread.sleep(1000);
System.out.println("T thread finish done.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
// runnable -> running|dead|blocked
t.start();
}
}
执行结果:t线程停止后,innerThread就会停止。