gpt4 book ai didi

Java ExecutorService 关闭现在需要很长时间

转载 作者:太空宇宙 更新时间:2023-11-04 07:02:20 26 4
gpt4 key购买 nike

我有一个 Java ExecutorService(固定线程池为 1),我将可运行任务传递到其中以供将来执行。每个任务通常在 10 秒内完成。 ExecutorService 只是简单地完成任务。如果我关闭我的应用程序,我会运行以下命令;

if (taskProcessor != null) {
taskProcessor.shutdownNow();
while (!taskProcessor.isTerminated()) {
// Wait For All Submitted Tasks To Finish
}
}

问题是它似乎需要很长时间才能关闭,有时可能需要几分钟,有时它似乎永远不会关闭,有时它会在几秒钟内关闭!执行程序队列中随时可能有多达 2000 个任务,但我只是希望它完成当前正在执行的任务并退出。我在这里做错了什么?

最佳答案

您没有按照正确的顺序关闭ExecutorService

您必须按照 oracle 建议的特定顺序调用 shutdownshutdownNowawaitTermination

void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}

关于Java ExecutorService 关闭现在需要很长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21911406/

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