等待两个期货/可运行债券/可赎回债券中的任何一个完成?

问题描述 投票:0回答:2

我如何一次将两个任务添加到执行器(或类似任务),然后等待两个任务中的任何一个完成(即最快),而另一个任务以及以前启动的任务继续执行背景?

我知道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
2个回答
2
投票
[如果您使用的是ExecutorCompletionService,请创建一个包装了ExecutorCompletionServiceExecutorService两个任务的新实例,然后调用submit

例如:

take()

public Future<String> submitPair(ExecutorService executorService) throws InterruptedException { ExecutorCompletionService<String> ecs = new ExecutorCompletionService<>(executorService); ecs.submit(() -> oneWay()); ecs.submit(() -> orAnother()); return ecs.take(); } 不需要额外的清理。


1
投票
CompletableFuture
© www.soinside.com 2019 - 2024. All rights reserved.