Java中线程可以分为用户线程和守护线程两类,如果某个JVM进程只有守护线程在运行,则进程会退出。
When we create a Thread in java program, it's known as user thread. A daemon thread runs in background and doesn't prevent JVM from terminating. When there are no user threads running, JVM shutdown the program and quits. A child thread created from daemon thread is also a daemon thread.
代码为例:
public class DeamonTester {
public class Thread1 implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("线程:" + Thread.currentThread().getName() + "工作");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Thread2 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("线程:" + Thread.currentThread().getName() + "工作");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String args[]){
DeamonTester d = new DeamonTester();
DeamonTester.Thread1 r1 = d.new Thread1();
DeamonTester.Thread2 r2 = d.new Thread2();
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
执行结果如下:
线程:Thread-1工作
线程:Thread-2工作
线程:Thread-2工作
线程:Thread-1工作
线程:Thread-2工作
线程:Thread-1工作
线程:Thread-2工作
线程:Thread-1工作
线程:Thread-2工作
线程:Thread-1工作
线程:Thread-1工作
线程:Thread-1工作
线程:Thread-1工作
线程:Thread-1工作
线程:Thread-1工作
......
Thread-1会一直执行不会停止。
因为Thread-1是一个用户线程。
如果我们进行如下的更改,把Thread-1的类型更改为守护线程。
public static void main(String args[]){
DeamonTester d = new DeamonTester();
DeamonTester.Thread1 r1 = d.new Thread1();
DeamonTester.Thread2 r2 = d.new Thread2();
Thread t1 = new Thread(r1);
t1.setDaemon(true);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
再看执行结果:
线程:Thread-1工作
线程:Thread-2工作
线程:Thread-2工作
线程:Thread-1工作
线程:Thread-1工作
线程:Thread-2工作
线程:Thread-1工作
线程:Thread-2工作
线程:Thread-2工作
线程:Thread-1工作
线程:Thread-1工作
可以看出,在Thread-2停止工作后,该进程只有Thread-1一个线程在工作,而Thread-1是守护线程,则JVM进程退出。Thread-1不再执行。