【发布时间】:2020-02-17 15:41:06
【问题描述】:
我在一个项目中找到了这段代码:
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 );
感谢您的解释。
【问题讨论】:
-
好吧,您的第二个代码 sn-p 都使用自定义
Executor(而第一个使用通用ForkJoinPool)并且似乎没有等待CompletableFuture完成(它也只启动一个任务,不像第一个 sn-p)。 -
后者创建一个任务,运行在一个有10个可用线程的executor上(即9个浪费线程,除非你在后续代码中多次提交),前者创建10个任务(通常使用一个普通的池)。
-
@Michael 在
process.run(queue)中,queue是一个有很多元素的BlockingQueue,所以使用CompletableFuture.runAsync(() -> { process.run(queue); }, threadPool );每个线程都不会调用process.run(queue)方法? -
没有。
#runAsync(Runnable, Executor)使用给定的Executor执行给定的Runnable。请注意,只有一个Runnable,这意味着只有一个任务分配给Executor。ExecutorService的所有标准实现每个任务使用一个线程。 -
@akuma8
queue与执行者和任务执行无关。队列中的元素数量无关紧要。
标签: java multithreading completable-future java-threads