简体   繁体   English

当一个任务在Threadpool执行程序中返回无效时,如何取消任务中的所有线程

[英]How to cancel all threads in tasks when one task returns invalid in Threadpool executor

I have arbitrary amount of tasks that I submit to a ThreadPoolExecutor. 我有提交给ThreadPoolExecutor的任意数量的任务。 Each of these tasks returns a code whether or not the task is successful. 无论任务是否成功,这些任务中的每一个都会返回一个代码。 What I'd like to happen is that the first task that returns a failure code will invalidate/cancel/interrupt all the other tasks, almost like short circuiting the whole thing to save time. 我想发生的事情是,返回失败代码的第一个任务将使其他所有任务无效/取消/中断,几乎就像将整个电路短路以节省时间一样。 If no tasks have failed, then all tasks will run. 如果没有任务失败,那么所有任务都将运行。 Assume that the tasks are designed to handle the interrupts gracefully 假定任务被设计为优雅地处理中断

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

I'm trying to think of a good design that would allow me to check on the returnValue and if it returns a failed value, to cancel work on the remaining tasks. 我试图考虑一个好的设计,该设计将允许我检查returnValue ,如果它返回失败的值,则可以取消其余任务的工作。

I can loop through all the futures and do a get() but this not what I want since it will block on that particular task until it finishes, but what if another task has already completed with a failed result? 我可以遍历所有期货并执行get()但这不是我想要的,因为它会阻塞该特定任务,直到完成为止,但是如果另一个任务已经完成但结果失败了怎么办?

What are the ways to accomplish this most efficiently? 有什么方法可以最有效地完成此任务?

EDIT: Possible duplicate question: In Java, how do I wait for all tasks, but halt on first error? 编辑:可能的重复问题: 在Java中,我如何等待所有任务,但是在出现第一个错误时停止?

If you use a ThreadPoolExecutor , it offers a hook beforeExecute() . 如果使用ThreadPoolExecutor ,它将在beforeExecute()提供一个钩子。 You can use that to check for an atomic flag (set by the failed task) to decide if you want to cancel the given Runnable . 您可以使用它来检查原子标记(由失败的任务设置),以确定是否要取消给定的Runnable Haven't actually tried it, but it might just work. 尚未实际尝试过,但它可能会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM