在JAVA中线程分为用户线程和守护线程. 用户线程会阻止 JVM的正常停止, 而守护线程不会.
所有守护线程一般用于重要性不是很高的任务, 如JVM的GC线程就是守护线程.
使用JAVA Thread类的setDameon(true)即可设置为守护线程
public class DaemonThread {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
System.out.println("线程working, 并休息20秒");
try {
Thread.sleep(1000 * 20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程finish");
}
};
t.setDaemon(true);//设置为守护线程, 不设置默认为用户线程
t.start();
}
}
执行如下:
线程working, 并休息20秒
可见JVM MAIN线程直接退出了.
下面看一下用户线程的效果
将t.setDaemon这行代码注释即可, 运行结果如下:
线程working, 并休息20秒
线程finish
证明了用户线程会阻止 JVM的正常停止