finally 不會執行的情況
在 Java 中,finally 有沒有可能不會執行的,試看看下麵的情況Java代碼
- public class TestFinally {
- private static class DaemonThread extends Thread {
- @Override
- public void run() {
- try {
- TimeUnit.MILLISECONDS.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- System.out.println("In finally");
- }
- }
- }
- public static void main(String args[]) {
- DaemonThread daemon = new DaemonThread();
- daemon.setDaemon(true);
- daemon.start();
- }
- }
運行結果並沒有打印"in finally",因為在主線程結束時,後台線程同樣被結束掉,finally沒有機會執行。
最後更新:2017-04-02 06:51:53