【问题标题】:How to make executerService.shutdown wait for nested threads invokation如何让 executorService.shutdown 等待嵌套线程调用
【发布时间】:2022-02-02 17:25:44
【问题描述】:

所以我有一个看起来像这样的函数

ExecutorService executorService = Executors.newFixedThreadPool(2000);
Boolean getMore = true;
try{
    While (getMore) {
       JSONObject response = getPaginatedResponse();
       int[] ar = response.get("something");
       if (ar.length > 0) {
           // loop through the array and invoke executorService.submit() for each
       }
       else { getMore = false; }
    }
    executorService.shutdown();
    try {
            System.out.println("waiting for tasks to complete, termination starting at : "+java.time.LocalDateTime.now());
            executorService.awaitTermination(15, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new Exception("loading was interrupted... thread pool timed out!");
        }

} catch (Exception) {
   System.out.println("Fatal error");
}

我的问题是这些线程中的每一个都会调用 x 个线程,而这些线程又会调用一个 API 并处理其响应,在所有“第一级”线程被触发后,实现会停止执行,但不一定是所有线程第二级,这对我的程序至关重要,我如何或在哪里调用 executerService.shutdown() 以确保调用了所有线程。

【问题讨论】:

  • 2000 个线程将适得其反,除非您的系统具有数百个处理器。
  • @JimGarrison 是的,我在可以支持它的系统上运行它,不用担心:D
  • 有时候,如果你找不到一个你想要的库,你必须自己编写代码。如果您想等待所有线程完成,那么为什么不声明一个 AtomicInteger numLiveThreads = new AtomicInteger(0); 在创建每个新线程之前递增,并让每个线程在它死亡之前递减它?然后,您可以通过轮询等待它们全部死亡,直到 numLiveThreads 变为零。
  • 我没有看到任何提交的调用,所以问题没有解释“第一级”和“第二级”线程的含义——这就是你的问题所在。您是否有重现此问题的最少代码?

标签: java multithreading executorservice


【解决方案1】:

您可以将 executorService.shutdown(); 放入 finally 异常块中

【讨论】:

  • 这会有什么不同?它仍然不会等待嵌套线程
猜你喜欢
  • 2016-04-11
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多