守护线程是为其他非守护线程的线程服务,当线程中不存在非守护线程时,则守护线程自动销毁。
守护线程结束时,不一定会执行finally语句。
import java.util.concurrent.ExecutionException;
/**
* 守护线程的使用和守护线程中的finally语句块
*/
public class DaemonThread {
private static class UseThread extends Thread {
@Override
public void run() {
try {
String threadName = Thread.currentThread().getName();
sleep(500);
System.out.println(threadName + " I am extends Thread !");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("执行finally !");
}
}
}
public static void main(String[] args) throws InterruptedException {
UseThread useThread = new UseThread();
useThread.setDaemon(true);
useThread.start();
System.out.println("Main thread end !");
}
}