ThreadpoolExecutor,正在运行的线程之一引发异常时,等待其他正在运行的线程完成

时间:2018-07-27 14:18:52

标签: java threadpoolexecutor

问题声明:我正在循环中使用 ThreadPoolExecutor 调用用于文本文件处理的窗口进程(Abby)。一次有5个正在运行的线程调用窗口处理。但是在某些情况下,一个或多个正在运行的线程会引发异常。 在这种情况下,我想允许其他正在运行的线程完成其任务,并且在运行线程完成后可以正常处理抛出异常的线程。 我该怎么做? 到目前为止,我知道一旦发生异常,我们可以使用 ThreadExecutionCompletionService 取消其他正在运行的线程 但是我的情况不同-我希望其他正在运行的线程完成

ExecutorService executorService = Executors.newCachedThreadPool();
final ExecutorCompletionService<String> completionService = 
            new ExecutorCompletionService<String>(executorService);
for (int i = 0; i < 10; ++i) {
    completionService.submit(new Task());
}

1 个答案:

答案 0 :(得分:0)

怎么样(请注意,您必须对其进行调整以供自己使用):

ExecutorService executorService = Executors.newCachedThreadPool();

List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
    futures.add(CompletableFuture.runAsync(
                     () -> {
                         // do work here and return
                         return work
                      },executorService)
                      .exceptionally(e -> {
                           logger.error("Error here"+e);
                           return null;
                       })
      );
}
CompletableFutre.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();