gpt4 book ai didi

java - 当线程被中断/杀死时,finally block 可能不会被执行吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:48:43 24 4
gpt4 key购买 nike

the Java tutorial它说 try { ... } 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.

一个线程是不是真的可以 interrupted killed ( I thought that was impossible? ) 这样 finally block 将不会在运行此线程的 JVM 退出时执行/杀了? (我很困惑,因为上面的引述对此非常明确,没有太大的误解空间。)

编辑:将问题分解为核心意图。

最佳答案

好吧,我认为正确。可以使用已弃用的方法:

@Test
public void testThread() throws Exception {
Thread thread = new Thread(new MyRunnable());
thread.start();
Thread.sleep(100);
thread.suspend();
Thread.sleep(2000);
}

class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Start");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("Done");
}
}
}

由于暂停(很可能)发生在线程 hibernate 时,finally block 将永远不会执行。

关于java - 当线程被中断/杀死时,finally block 可能不会被执行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19501044/

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