在java线程中有两种线程,一直是用户线程,一种是守护线程。
当线程中不存在非守护线程了,那么守护线程也会自动销毁。典型的守护线程就是垃圾回收线程。
以前两篇介绍suspend和resume的博客为例,有以下示例:
public class Mythread extends Thread{
private long i = 0;
@Override
public void run(){
while (true) {
i++;
System.out.println(i);
}
}
}
public class Main {
public static void main(String[] args) {
Mythread mythread = new Mythread();
try {
//mythread.setDaemon(true);
mythread.start();
Thread.sleep(1000);
mythread.suspend();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
线程mythread被suspend了,那么,因为println里面有锁的缘故,线程没有办法往下走,一直停留在这里:
当吧mythread线程设置成守护线程,即把上面的
//mythread.setDaemon(true);
注释去掉,线程会终止:
因为main方法已经结束了,守护线程会自动销毁。