繁体   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