gpt4 book ai didi

java - 执行服务 shutdownNow ,它是如何工作的

转载 作者:行者123 更新时间:2023-12-05 05:14:21 25 4
gpt4 key购买 nike

根据方法 shutdownNow (ExecutorService) 的文档

There are no guarantees beyond best-effort attempts to stop
processing actively executing tasks. For example, typical
implementations will cancel via {@link Thread#interrupt}, so any
task that fails to respond to interrupts may never terminate

我有以下代码:

public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newSingleThreadExecutor(r -> {
final Thread thread = new Thread(r);
thread.setDaemon(false);
return thread;
});
service.submit(() -> {
while (true) {
Thread.sleep(1000);
System.out.println("Done: " + Thread.currentThread().isInterrupted());
}
});
Thread.sleep(3000);
service.shutdownNow();
}

这是输出:

Done: false
Done: false

两个循环后停止执行。shutdownNow 如何中断我的工作,我只有无限循环,没有检查 Thread.currentThread.isInterrupted();

在我看来,shutdownNow只调用工作线程的中断方法

最佳答案

Thread.sleep() 检查 .isInterrupted() 并在被中断时抛出 InterruptedException。您的 lambda 隐式地 throws InterruptedException,因此当执行程序关闭时它永远不会到达您的 System.out.println。您可以浏览source for ThreadPoolExecutor看看这是怎么发生的。

关于java - 执行服务 shutdownNow ,它是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52620399/

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