【问题标题】:CompletableFuture.runAsync vs array of CompletableFutureCompletableFuture.runAsync vs CompletableFuture 数组
【发布时间】: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(() -&gt; { process.run(queue); }, threadPool ); 每个线程都不会调用process.run(queue) 方法?
  • 没有。 #runAsync(Runnable, Executor) 使用给定的Executor 执行给定的Runnable。请注意,只有一个Runnable,这意味着只有一个任务分配给ExecutorExecutorService 的所有标准实现每个任务使用一个线程。
  • @akuma8 queue 与执行者和任务执行无关。队列中的元素数量无关紧要。

标签: java multithreading completable-future java-threads


【解决方案1】:
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 );

在这种情况下,您正在指定线程池中执行代码。

这些代码块的区别

  • 它们在不同的线程池中执行(第一个是常见的 ForkJoin,它是可完成期货的默认设置,第二个是指定的线程池)
  • 在第一种情况下,您正在等待一组任务完成,在第二种情况下 - 您只是异步运行任务

【讨论】:

  • 第二种情况没用吗?由于池中只有一个线程会处理该任务。我的意思是所有线程都不会执行process.run(queue) 方法。
  • 唯一的用途是第二种情况在其他线程中运行process.run(queue)(这在某些情况下可能很有用),但是CompletableFuture.runAsync的结果被忽略了,所以这样做没有意义这样。没有 CompletableFuture 也可以达到相同的结果,即threadPool.submit(() -&gt; process.run(queue))
猜你喜欢
  • 2020-08-07
  • 2019-07-18
  • 2016-12-09
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 2020-02-17
  • 2015-11-03
  • 2019-01-09
相关资源
最近更新 更多