ExecutorService - 如何在其中一个异常发生后中断从主线程调用的线程的执行

ExecutorService - How to interrupt exectuion of threads which have been invoked from main thread after an exception inside one of them

我有classSomeService。它的方法可以从 不同的线程 调用(例如从 RestController)。 这个 class 包含 ExecutorService 和一些 CustomClass.

public class SomeService {
   private ExecutorService service;
   private CustomClass customClass;

   public SomeService(ExecutorService service, CustomClass customClass){
       this.service = service;
       this.customClass = customClass;
   }

   public void servicePost() {
      CountDownLatch countDownLatch = new CountDownLatch(urls.size());
      for (String url : List<String> urls){
          service.submit(() -> {
              customClass.send(url);
              countDownLatch.countDown();
          });
      }
      countDownLatch.await();
   }
}

我想使用 ExecutorService 在不同线程中并行执行 customClass.send(url) 但此方法可能会抛出 RuntimeException.

比如我提交了5个任务:
1. 2个任务执行成功
2. 2个任务是运行.
3.其中之一抛出RuntimeException。

如何中断 运行 的任务?
p.s。 ExecutorService 可以有来自其他线程的任务。我不想打扰他们。

你可以在捕获到异常时在执行器服务上调用shutdownNow(),也需要在处理之前检查任务内部的Thread#interrupted()。您的代码应如下所示:

service.submit(() -> {
        if (!Thread.interrupted()) {
            try {
                  customClass.send(url);
                  countDownLatch.countDown();
                } catch (Exception e) {
                   service.shutdownNow();
                }
        }

    });