加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如果运行该函数的线程中断,finally块是否执行?

发布时间:2020-12-14 05:39:12 所属栏目:Java 来源:网络整理
导读:如果我有一个具有try / finally部分的功能,并且运行它的线程在try块中被中断,finally块是否在中断实际发生之前执行? 解决方法 According to the Java Tutorials,“如果执行try或catch代码的线程被中断或者被杀死,即使整个应用程序整体继续,finally块可能不
如果我有一个具有try / finally部分的功能,并且运行它的线程在try块中被中断,finally块是否在中断实际发生之前执行?

解决方法

According to the Java Tutorials,“如果执行try或catch代码的线程被中断或者被杀死,即使整个应用程序整体继续,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.

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();

它打印 – 最后执行

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读