如果运行该函数的线程被中断,finally块是否会执行? [英] Does the finally block execute if the thread running the function is interrupted?
问题描述
如果我有一个带有try / finally部分的函数,并且运行它的线程在try块中被中断,那么finally块是否会在中断实际发生之前执行?
If I have a function with a try/finally section, and the thread running it is interrupted while in the try block, will the finally block execute before the interruption actually occurs?
推荐答案
根据Java教程,如果执行尝试
或 catch
代码的线程被中断或终止, finally
块可能无法执行,即使整个应用程序仍在继续。
According to the Java Tutorials, "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."
这是完整的段落:
最后
块总是在<$ c $时执行c>尝试阻止退出。这个
确保即使出现意外的
异常也会执行finally
块。但是finally
不仅仅是例外
处理 - 它允许程序员避免使用> return ,
继续
,或break
。将清理
代码放在finally
块中总是一个好习惯,即使预计没有
例外。
The
finally
block always executes when thetry
block exits. This ensures that thefinally
block is executed even if an unexpected exception occurs. Butfinally
is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by areturn
,continue
, orbreak
. Putting cleanup code in afinally
block is always a good practice, even when no exceptions are anticipated.
注意:如果JVM在尝试
或 catch
时退出代码正在执行,然后
finally
块可能无法执行。同样,如果执行
的线程尝试
或 catch
代码被中断或终止, finally
阻止可能
即使整个应用程序继续执行也不会执行。
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();
打印 - 最后执行
这篇关于如果运行该函数的线程被中断,finally块是否会执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!