【问题标题】:Wait for any of two Futures/Runnables/Callables to complete?等待两个 Futures/Runnables/Callables 中的任何一个完成?
【发布时间】:2019-11-26 13:57:54
【问题描述】:

如何一次将两个任务添加到 Executor(或类似的),然后等待两个中的任何一个完成(即最快),而另一个以及之前启动的任务继续在后台?

我知道 CompletionService 提供了类似的东西,但我能做的就是等待下一个完成,.take()。在我的情况下,这可能来自以前的计划,而不是我需要等待的计划之一。

我想要的伪代码

ExecutorService executorService = Executors.newFixedThreadPool(100);
Future<?> one = executorService.submit(() -> oneWay());
Future<?> two = executorService.submit(() -> orAnother());

Future theFirstOneToFinish = waitFor(one, two);
// one done, the other one keeps on working
return theFirstOneToFinish;

【问题讨论】:

    标签: java concurrency parallel-processing


    【解决方案1】:

    CompletionService 仅监督它提交的那些任务。换句话说,您可以为您提交的每对任务创建一个新任务,然后调用take() 来检索第一个完成的任务。

    如果您正在使用ExecutorCompletionService,请创建一个新实例来包装您的ExecutorServicesubmit 两个任务,然后调用take()

    例如:

    public Future<String> submitPair(ExecutorService executorService) throws InterruptedException {
        ExecutorCompletionService<String> ecs = new ExecutorCompletionService<>(executorService);
        ecs.submit(() -> oneWay());
        ecs.submit(() -> orAnother());
        return ecs.take();
    }
    

    ExecutorCompletionService 不需要额外的清理。

    【讨论】:

      【解决方案2】:

      使用CompletableFuture

      ExecutorService executorService = Executors.newFixedThreadPool(100);
      CompletableFuture<?> one = CompletableFuture.supplyAsync(() -> oneWay(),  executorService);
      CompletableFuture<?> two = CompletableFuture.supplyAsync(() -> orAnother(),  executorService);
      
      return CompletableFuture.anyOf(one, two);
      

      【讨论】:

      • 缺点是现在oneWay()orAnother() 不再允许抛出已检查的异常。并且不支持取消。
      • @Holger 我不认为他们可以像在 OP 中那样提交到 ExecutorService 时抛出已检查的异常,因为他创建了一个 Runnable lambda。
      • 不,当这些方法返回一个值时,submit 意味着创建一个Callable,这可能会引发检查异常。由于您使用的是supplyAsync 而不是runAsync,因此您也假设它们返回一个值。
      猜你喜欢
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      相关资源
      最近更新 更多