</pre><pre name="code" class="java">
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) {
Thread t = new Thread(new ADaemon());
t.setDaemon(true);
t.start();
}
}
这是一个后台线程在不执行finally子句的情况下就会终止其run()方法;
当运行这个程序时,finally子句是不会执行的,但是如果把注释掉对setDaimon()的调用,就会看到finally子句的执行。
摘自《java编程思想》21章并发