gpt4 book ai didi

java - 在阻塞队列上等待时中断

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

我有一个从 Executor 运行的 Runnable
可运行对象被阻塞,在 SychronousQueue.take 中等待。如何确保执行 executor.shutdowntake 会被中断?

最佳答案

+1 给@Eugene。 ExecutorService.shutdown() 关闭线程池,但任何提交的作业将继续运行直到完成。如果您使用shutdownNow()相反,它实际上会中断线程。这并不意味着它们会立即停止,而是意味着如果它们在 queue.take() 中或下次调用 queue.take() 时被阻塞,将抛出 InterruptedException,以便线程可以退出。

引用 Javadocs:

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

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

当您的线程调用 queue.take() 时,它们应该具有类似于以下代码的内容:

  try {
work = queue.take();
...
} catch (InterruptedException e) {
// re-interrupt the thread which is always a good pattern
Thread.currentThread().interrupt();
// quit the processing thread
return;
}

关于java - 在阻塞队列上等待时中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15635114/

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