【问题标题】:How to cancel all threads in tasks when one task returns invalid in Threadpool executor当一个任务在线程池执行器中返回无效时如何取消任务中的所有线程
【发布时间】:2013-07-03 17:51:52
【问题描述】:

我有任意数量的任务提交给 ThreadPoolExecutor。无论任务是否成功,这些任务中的每一个都会返回一个代码。我想要发生的是,返回失败代码的第一个任务将使所有其他任务无效/取消/中断,几乎就像将整个事情短路以节省时间。如果没有任务失败,则所有任务都将运行。假设任务被设计为优雅地处理中断

for(int i = 0; i < size; i++) {
  Future<?> future = executor.submit(new Runnable() {
    @Override
     public void run() {
         returnValue = performWork();
         if(returnValue == FAILED)
             // signal cancel other tasks??
     }  
   });

   futureTaskList.add(future);
}

我正在尝试一个好的设计,让我可以检查returnValue,如果它返回失败的值,则取消剩余任务的工作。

我可以遍历所有期货并执行get(),但这不是我想要的,因为它会阻止该特定任务直到它完成,但如果另一个任务已经完成但结果失败怎么办?

最有效的方法是什么?

编辑: 可能重复的问题:In Java, how do I wait for all tasks, but halt on first error?

【问题讨论】:

标签: java multithreading concurrency threadpoolexecutor


【解决方案1】:

如果你使用ThreadPoolExecutor,它会提供一个钩子beforeExecute()。您可以使用它来检查原子标志(由失败的任务设置)来决定是否要取消给定的Runnable。还没有真正尝试过,但它可能会起作用。

【讨论】:

    猜你喜欢
    • 2021-04-11
    • 2013-07-22
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 2012-09-03
    • 2015-04-24
    相关资源
    最近更新 更多