【问题标题】:How to set countdownlatch for unknown number of threads如何为未知数量的线程设置倒计时
【发布时间】:2019-12-25 12:42:37
【问题描述】:

我必须启动未知数量的线程,然后等待或所有线程完成它们的工作。我正在使用执行者服务。我尝试使用 countdownlatch - 这样我就可以等到倒计时为零。 但是我无法获得已启动的线程数。有人可以告诉我如何实现这一目标吗?

【问题讨论】:

  • 为什么不改用Futures
  • 能否分享您尝试过的代码。无法理解需求。

标签: java multithreading concurrency


【解决方案1】:

感谢您的回复。我遇到了答案,它有所帮助。分享一个链接供参考。 Flexible CountDownLatch?

【讨论】:

    【解决方案2】:

    如果您想合并CompletableFutures 的列表,您可以这样做:

    // Waits for *all* futures to complete and returns a list of results.
    // If *any* future completes exceptionally then the resulting future will also complete exceptionally.
    
    public static <T> CompletableFuture<List<T>> all(List<CompletableFuture<T>> futures) {
        CompletableFuture[] cfs = futures.toArray(new CompletableFuture[futures.size()]);
    
        return CompletableFuture.allOf(cfs)
                .thenApply(ignored -> futures.stream()
                                        .map(CompletableFuture::join)
                                        .collect(Collectors.toList())
                );
    }
    

    有关 Future 和 CompletableFuture 的更多详细信息,有用的链接:

    1. 未来:https://www.baeldung.com/java-future
    2. CompletableFuture:https://www.baeldung.com/java-completablefuture
    3. CompletableFuture:https://www.callicoder.com/java-8-completablefuture-tutorial/
    4. Waiting on a list of Future

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-28
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多