看看下面的代码
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();
}
}
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();
}
}
finally 总是会执行。
你自己可以测试下啊。如果你是在try的外面出错了
那么finally肯定不执行喽!
ADaemon睡觉的时候 main已经退出了
等睡醒时 发现运行的只有ADaemon 因是守护线程 jvm退出 后面不会运行了