看看下面的代码
import java.util.concurrent.*;public class ADaemon implements Runnable {
public void run() {
try {
System.out.println("Starting ADaemon");
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.println("Exiting via InterruptedException");
} finally {
System.out.println("This should always run?");
}
} public static void main(String[] args) throws Exception {
Thread t = new Thread(new ADaemon());
t.setDaemon(true);
t.start();
}
}

解决方案 »

  1.   

    在try中无论是否出现异常
    finally 总是会执行。
    你自己可以测试下啊。如果你是在try的外面出错了
    那么finally肯定不执行喽!
      

  2.   

    当正在运行的线程都是守护线程时,Java 虚拟机退出。
    ADaemon睡觉的时候 main已经退出了
    等睡醒时 发现运行的只有ADaemon 因是守护线程 jvm退出 后面不会运行了