簡體   English   中英

CompletableFuture.runAsync 與 CompletableFuture 數組

[英]CompletableFuture.runAsync vs array of CompletableFuture

我在一個項目中找到了這段代碼:

int threadCount = 10;
CompletableFuture<?>[] futures = new CompletableFuture<?>[threadCount];
for (int i = 0; i < threadCount; i++) {
    futures[i] = CompletableFuture.runAsync(() -> { process.run(queue); });
}
// Wait all futures
CompletableFuture.allOf(futures).join();

這樣做有什么區別?

ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
CompletableFuture.runAsync(() -> { process.run(queue); }, threadPool );

謝謝你的解釋。

int threadCount = 10;
CompletableFuture<?>[] futures = new CompletableFuture<?>[threadCount];
for (int i = 0; i < threadCount; i++) {
    futures[i] = CompletableFuture.runAsync(() -> { process.run(queue); });
}
// Wait all futures
CompletableFuture.allOf(futures).join();

在這種情況下,您創建一組可完成的期貨,這些期貨是在公共 ForkJoin 池中執行異步代碼的結果。 然后過程等待,直到所有期貨完成。

ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
CompletableFuture.runAsync(() -> { process.run(queue); }, threadPool );

在這種情況下,您正在執行指定線程池中的代碼。

這些代碼塊之間的區別

  • 它們在不同的線程池中執行(第一個是公共 ForkJoin,這是可完成期貨的默認值,第二個在指定的線程池中)
  • 在第一種情況下,您正在等待一組任務完成,在第二種情況下 - 您只是異步運行任務

暫無
暫無

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

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