簡體   English   中英

等待兩個 Futures/Runnables/Callables 中的任何一個完成?

[英]Wait for any of two Futures/Runnables/Callables to complete?

我如何一次添加兩個任務到一個 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;

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不需要額外的清理。

使用CompletableFuture

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

return CompletableFuture.anyOf(one, two);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM