我在一个项目中发现了以下代码:
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 );谢谢你的解释。
发布于 2020-02-20 01:27:25
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 );在这种情况下,您将在指定的线程池中执行代码。
这些代码块之间的差异
https://stackoverflow.com/questions/60265870
复制相似问题