一般情况下,try catch finally 语句块中的finally一般都会执行的,即便try或者catch中有return语句,当try catch中使用System.exit()结束的时候,则不会执行finally语句块。这点相信大家都挺清楚的。不过,当finally语句块是在Daemon 后台子线程中的run()被执行被执行的时候,情况就有点不一样。
Java Daemon 后台子线程结束时不执行finally语句。
就这个问题,刚好写了个小Demo灌灌水。
Main()中开启了一个Daemon线程,每隔一毫秒打印一次,主线程中睡5毫秒后打印end结束,Daemon线程直接退出,不打印finally。
class ThreadDaemonDemo extends Thread {
@Override
public void run() {
System.out.println(this + " is daemon " + isDaemon());
try {
while (true) {
Thread.sleep(1);
System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("finally "); //this part will not reach
}
}
}
public class TestThread {
public static void main(String args[]) {
Thread t1 = new ThreadDaemonDemo();
t1.setDaemon(true); // setDaemon() must be called before start()
t1.start();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end ......");
}
}
附上本人机器的结果
Thread[Thread-0,5,main] is daemon true
1490020816896 Thread-0
1490020816898 Thread-0
1490020816899 Thread-0
1490020816900 Thread-0
end ......