当在一个JVM进程里面开多个线程时,这些线程被分成两类:守护线程和非守护线程。默认都是非守护线程。
在Java中有一个规定:当所有的非守护线程退出后,整个JVM进程就会退出。意思就是守护线程“不算作数”,守护线程不影响整个 JVM 进程的退出。
例如,垃圾回收线程就是守护线程,它们在后台默默工作,当开发者的所有前台线程(非守护线程)都退出之后,整个JVM进程就退出了。
对于下面的程序,在thread.start()前面加一行代码thread.setDaemon(true)。当main(...)函数退出后,线程thread就会退出,整个进程也会退出。
package com.lagou.concurrent.demo;
public class Main {
public static void main(String[] args) {
MyDaemonThread myDaemonThread = new MyDaemonThread();
// 设置为daemon线程
myDaemonThread.setDaemon(true);
myDaemonThread.start();
// 启动非daemon线程,当非daemon线程结束,不管daemon线程是否结束,都结束JVM进
程。
new MyThread().start();
}
}
package com.lagou.concurrent.demo;
public class MyDaemonThread extends Thread {
@Override
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.lagou.concurrent.demo;
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("非Daemon线程");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}