简体   繁体   English

如何使用ExecutorService来处理中止的Runnable?

[英]How to use ExecutorService to handle an aborted Runnable?

I have a Worker class that implements Runnable and has a run() method which may raise exceptions in the event of a conflict, and return early. 我有一个implements RunnableWorker类,并且有一个run()方法,可以在发生冲突时引发异常,并提前返回。 When it does, that thread needs to be put back into the queue to be run again. 如果是,则需要将该线程放回队列中再次运行。

From looking at this question, it seems I need to rewrite with Callable . 从查看这个问题,我似乎需要用Callable重写。 Is that correct? 那是对的吗? There's no way to do this with Runnable ? 使用Runnable无法做到这一点?

Well you can have the worker thread do it itself. 那么你可以让工作线程自己做。 If you have control of the executor. 如果你有执行者的控制权。

class RequeableWorker implement Runnable{
  private final ExecutorService e;
  public RequeableWorker(ExecutorService e){this.e =e;}

  public void run(){
     try{
        //do work
     }catch(RuntimeException ex){
        e.submit(this);
        throw ex;
     }
  }
}

Or as your answer suggests having the waiting thread of a Future re-queue. 或者你的答案建议让Future的等待线程重新排队。

public void workOrRequeue(){
    for(;;){
       Future<?> future = e.submit(someCallable());
       try{
          future.get();
          return;
       }catch(ExecutionException ex){
          //maybe log, ex.printStackTrace();
       }
    }
}

As say the docs for Future.get() : 正如Future.get()的文档Future.get()

Throws: 抛出:

[...] [...]

ExecutionException - if the computation threw an exception ExecutionException - 如果计算引发异常

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

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