我如何一次将两个任务添加到执行器(或类似任务),然后等待两个任务中的任何一个完成(即最快),而另一个任务以及以前启动的任务继续执行背景?
我知道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;
ExecutorCompletionService
,请创建一个包装了ExecutorCompletionService
,ExecutorService
两个任务的新实例,然后调用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();
}
不需要额外的清理。
CompletableFuture