1

类 DaemonThread 扩展线程 {

public void run() {
    System.out.println("Entering run method");

    try {
        System.out.println("In run Method: currentThread() is"
            + Thread.currentThread());

        while (true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException x) {
                System.out.println("hi");
            }

            // System.out.println("In run method: woke up again");

            finally {
                System.out.println("Leaving run1 Method");
            }
        }
    } finally {
        System.out.println("Leaving run Method");
    }

}

public static void main(String[] args) {
    System.out.println("Entering main Method");

    DaemonThread t = new DaemonThread();
    t.setDaemon(true);
    t.start();

    try {
        Thread.sleep(900);
    } catch (InterruptedException x) {}

    System.out.println("Leaving main method");
}

}

为什么第二个 finally 方法不运行...我知道 finally 方法必须必须运行任何条件..但在这种情况下只有第一个 finally 方法,为什么不运行第二个 finally 方法。

4

5 回答 5

6

由于永远不会结束的循环,该println语句永远不会到达!while(true)

如果您离开该循环,则将执行第二个finally块。

于 2012-05-21T07:06:48.837 回答
2

理论上它应该运行第二个 finally 方法,但是由于它超出了永远不会结束的 while(true) 循环,因此无法访问它。

于 2012-05-21T07:10:37.503 回答
0

您的代码显示您的while循环不会结束。因此,不存在到达外部finally区块的问题。

只需使用任何其他条件,您可能会得到想要实现的目标。例如:

public void run() {
    System.out.println("Entering run method");
    int flag = 1;
    try {
        System.out.println("In run Method: currentThread() is"
            + Thread.currentThread());

        while (flag == 1) {
            try {
                Thread.sleep(500);
                 flag = 0;
            } catch (InterruptedException x) {
                System.out.println("hi");
            }

            // System.out.println("In run method: woke up again");

            finally {
                System.out.println("Leaving run1 Method");
            }
        }
    } finally {
        System.out.println("Leaving run Method");
    }

}
于 2012-05-21T07:08:50.677 回答
0

它永远不会执行 finally 块,因为 while 循环始终为 TRUE。此外,来自 java 注释

"if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues."
于 2012-05-21T07:09:59.317 回答
0

我猜你希望在 JVM 退出时,因为线程是守护进程,会自动优雅地退出循环。那不是真的。守护线程简单地死掉(在当前执行的代码中的位置)

于 2012-05-21T07:12:06.133 回答