[英]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 Runnable
的Worker
类,并且有一个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 exceptionExecutionException
- 如果计算引发异常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.