gpt4 book ai didi

java - 如何在完成当前执行的任务后关闭 CompletionService

转载 作者:行者123 更新时间:2023-11-30 06:54:43 24 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");

在调用shutdown 之后,所有提交的任务都会被执行。如果我调用 shutdownNow,则当前执行的线程将抛出 java.lang.InterruptedException

有什么方法可以等待当前执行的任务完成而不执行其他提交的任务吗?

最佳答案

shutdown()允许当前提交的任务完成,但拒绝新任务:

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

如果你想在你的线程中等待执行器关闭,你可以调用executor.awaitTermination(long timeout, TimeUnit unit) :

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

如果您想让当前正在运行的任务完成,但丢弃已经提交到队列的任务,您有几个选择:

  • 使用 cancel(false) 取消 future :

    Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run.

    Returns: false if the task could not be cancelled, typically because it has already completed normally; true otherwise

  • 用自定义的 CancellableRunnable/Callable 包装你的 Runnable/Callable(取决于你的 getTask() 返回):

    class CancellableRunnable implements Runnable {

    private final AtomicBoolean shouldRun;
    private final Runnable delegate;

    public CancellableRunnable(AtomicBoolean shouldRun, Runnable delegate) {
    this.shouldRun = shouldRun;
    this.delegate = delegate;
    }

    @Override
    public void run() {
    if (shouldRun.get()) {
    delegate.run();
    }
    }
    }

    以及您示例中的用法:

    AtomicBoolean shouldRun = new AtomicBoolean(true);
    while (i < 40) {
    completionService.submit(new CancellableRunnable(shouldRun, getTask()));
    i++;
    }
    shouldRun.set(false);
    executor.shutdown();

关于java - 如何在完成当前执行的任务后关闭 CompletionService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36081685/

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