如果我有一个具有try / finally部分的功能,并且运行它的线程在try块中被中断,finally块是否在中断实际发生之前执行?
解决方法
According to the Java Tutorials,“如果执行try或catch代码的线程被中断或者被杀死,即使整个应用程序整体继续,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.Note: If the JVM exits while the
try
orcatch
code is being executed,then
thefinally
block may not execute. Likewise,if the thread executing
thetry
orcatch
code is interrupted or killed,thefinally
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();
它打印 – 最后执行