如果运行该函数的线程被中断,finally块是否会执行? [英] Does the finally block execute if the thread running the function is interrupted?

查看:1419
本文介绍了如果运行该函数的线程被中断,finally块是否会执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个带有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 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.

注意:如果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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆