gpt4 book ai didi

java - 如果运行该函数的线程被中断,finally block 是否会执行?

转载 作者:太空狗 更新时间:2023-10-29 22:45:58 25 4
gpt4 key购买 nike

如果我有一个带有 try/finally 部分的函数,并且运行它的线程在 try block 中被中断,finally block 是否会在中断实际发生之前执行?

最佳答案

According to the Java Tutorials , "如果执行 trycatch 代码的线程被中断或杀死,则 finally block 可能不会执行,即使整个应用程序也是如此继续。”

全文如下:

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, 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.

class Thread1 implements Runnable {

@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("finally executed");
}
}
}

...

t1.start();
t1.interrupt();

它打印 - 最终执行

关于java - 如果运行该函数的线程被中断,finally block 是否会执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14576765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com