[英]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这些代码块之间的区别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.