首页 > 解决方案 > 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());
}

标签: javathreadpoolexecutor

解决方案


怎么样(请注意,您必须根据自己的用途进行调整):

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();

推荐阅读