我在项目中找到了这段代码:
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();
在这种情况下,您创建了一组可完成的 future,它们是在公共(public) ForkJoin 池中执行异步代码的结果。然后进程等待,直到所有 future 完成。
ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
CompletableFuture.runAsync(() -> { process.run(queue); }, threadPool );
在这种情况下,您正在指定的线程池中执行代码。
这些代码块之间的差异
- 它们在不同的线程池中执行(第一个在公共(public) ForkJoin 中,这是可完成的 future 的默认值,第二个在指定的线程池中执行)
- 在第一种情况下,您正在等待一组任务完成,在第二种情况下 - 您只是异步运行任务
关于java - CompletableFuture.runAsync 与 CompletableFuture 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60265870/