[英]How to set countdownlatch for unknown number of threads
我必須啟動未知數量的線程,然后等待或所有線程完成它們的工作。 我正在使用執行程序服務。 我嘗試使用 countdownlatch - 這樣我就可以等到倒計時為零。 但是我無法獲得已啟動的線程數。 有人可以告訴我如何實現這一目標嗎?
謝謝你的回復。 我遇到了答案,它有所幫助。 分享一個鏈接以供參考。 靈活的倒計時閂鎖?
如果您想組合CompletableFutures
列表,您可以這樣做:
// Waits for *all* futures to complete and returns a list of results.
// If *any* future completes exceptionally then the resulting future will also complete exceptionally.
public static <T> CompletableFuture<List<T>> all(List<CompletableFuture<T>> futures) {
CompletableFuture[] cfs = futures.toArray(new CompletableFuture[futures.size()]);
return CompletableFuture.allOf(cfs)
.thenApply(ignored -> futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList())
);
}
有關 Future 和 CompletableFuture 的更多詳細信息,有用的鏈接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.