类 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 不运行。
最佳答案
println
语句永远不会到达,因为 while(true)
循环永远不会结束!
如果你离开那个循环,那么第二个 finally
block 将被执行。
关于java - Java 中带有 try 的 finally 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10680773/