gpt4 book ai didi

java - 如何关闭 CompletionService

转载 作者:行者123 更新时间:2023-11-29 07:35:48 26 4
gpt4 key购买 nike

我需要做这样的事情:

ExecutorService executor = Executors.newFixedThreadPool(2);
CompletionService<Boolean> completionService = new ExecutorCompletionService<>(executor);
int i = 0;
while (i < 40) {
completionService.submit(getTask());
i++;
}
executor.shutdown();
System.out.println("SHUTDOWN");

但是在 executor 对象上调用 shutdown 之后 completionService 仍然执行任务。

我怎样才能让它停止?

有没有办法停止ExecutorService,等待当前正在执行的任务完成?

最佳答案

ExecutorService 将继续执行已经提交的任务,但不允许提交更多任务,来自 documentation

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.
emphasis mine

所以您已经提交了 40 个任务,这些任务将在关机前执行。

如果你想强制关机。您可以使用 shutdownNow :

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

这将根据需要放弃计划任务。

注意:停止进行中的任务完全是另一个问题。

关于java - 如何关闭 CompletionService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36079519/

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