我如何一次将两个任务添加到一个执行器(或类似任务),然后等待两个任务中的任何一个完成(即最快),而另一个任务以及之前启动的任务仍在继续在后台?
我知道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;
答案 0 :(得分:2)
CompletionService
仅监督它提交的那些任务。换句话说,您可以为提交的每对任务创建一个新任务,并调用take()
以检索完成的第一个任务。
如果您使用的是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();
}
ExecutorCompletionService
不需要其他清理。
答案 1 :(得分:1)
使用CompletableFuture
。
ExecutorService executorService = Executors.newFixedThreadPool(100);
CompletableFuture<?> one = CompletableFuture.supplyAsync(() -> oneWay(), executorService);
CompletableFuture<?> two = CompletableFuture.supplyAsync(() -> orAnother(), executorService);
return CompletableFuture.anyOf(one, two);