简体   繁体   English

CompletableFuture.runAsync 与 CompletableFuture 数组

[英]CompletableFuture.runAsync vs array of CompletableFuture

I found this code in a project:我在一个项目中找到了这段代码:

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();

What's the difference with doing this?这样做有什么区别?

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

Thanks for your explanation.谢谢你的解释。

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();

In this case, you creates set of completable futures which are result of executing asynchronous code in common ForkJoin pool.在这种情况下,您创建一组可完成的期货,这些期货是在公共 ForkJoin 池中执行异步代码的结果。 Then process waits until all futures are completed.然后过程等待,直到所有期货完成。

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

In this case, you are executing code in specified thread pool.在这种情况下,您正在执行指定线程池中的代码。

The differences between these code blocks这些代码块之间的区别

  • They are executed in different thread pools (first in common ForkJoin which is default for completable futures, second in specified thread pool)它们在不同的线程池中执行(第一个是公共 ForkJoin,这是可完成期货的默认值,第二个在指定的线程池中)
  • In first case you are waiting for set of tasks to be completed, in second - you just running task asynchronously在第一种情况下,您正在等待一组任务完成,在第二种情况下 - 您只是异步运行任务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM