如果一个线程抛出异常,那么如何停止其他等待线程

时间:2018-05-21 02:19:23

标签: java multithreading exception exception-handling

在Java中如果我有三个线程 t1,t2 t3 。假设 t1 正在执行某项任务而 t2,t3 处于等待状态。现在如果 t1 面临/抛出任何类型的异常,那么我不想执行我的 t2,t3 线程。

我们如何在Java中实现此功能?

1 个答案:

答案 0 :(得分:1)

不要直接使用线程,请使用执行器框架。

具体来说,使用CompletionService,以便您可以按顺序(成功或其他方式)检索您提交给执行者的任务。

而不是:

Thread t1 = new Thread(() -> { /* runnable 1 */ });
Thread t2 = new Thread(() -> { /* runnable 2 */ });
Thread t3 = new Thread(() -> { /* runnable 3 */ });

创建CompletionService

ExecutorService executor = ...;  // e.g. Executors.newFixedThreadPool
CompletionService completionService = new CompletionService(executor);

现在,创建一个列表,通过向Future提交任务来保留返回的CompletionService

List<Future<?>> futures = new ArrayList<>();
futures.add(completionService.submit(() -> { /* runnable 1 */ })); 
futures.add(completionService.submit(() -> { /* runnable 2 */ })); 
futures.add(completionService.submit(() -> { /* runnable 3 */ }));

现在,使用take按顺序获得期货:

for (int i = 0; i < futures.size(); ++i) {
  Future<?> completed = futures.take();
  try {
    completed.get();
  } catch (ExecutionException e) {
    // An exception occurred whilst running the task.
    // Cancel all the tasks.
    futures.forEach(f -> f.cancel(true));
  }
}

当然,要让cancel在这里做任何有用的事情,你需要你的runnables来检查中断;但无论如何,你需要有一些方法来检查你的其他线程中的“失败”。