我有一个处理某些任务的ExecutorService
。客户端主题可以在shutdown()
上调用ExecutorService
。我希望在ExecutorService
完全关闭后运行一些清理代码。是否存在在ExecutorService
完成关闭后运行回调方法的机制。
注意:
shutdownNow()
shutdown()
完成后运行。ExecutorService
是newCachedThreadPoolExecutor()
; 答案 0 :(得分:2)
启动另一个线程/ executor-managed-runnable,在循环中的try-catch语句中检查ExecutorService.awaitTermination(...)
,直到它返回true
,然后运行关闭处理代码。循环是必要的,因为该方法可能在中断时过早返回。
这样的事情:
public class ShutdownHandler implements Runnable {
private final ExecutorService service;
public ShutdownHandler(final ExecutorService service) {
this.service = service;
}
@Override
public void run() {
boolean terminated = false;
while (!terminated) {
try {
terminated = service.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (final InterruptedException ex) {
// check again until terminated
}
}
// your shutdown handling code here
}
}
答案 1 :(得分:1)
我会扩展和覆盖:
public class MyExecutorService extends ThreadPoolExecutor {
@Override
public void shutdown() {
super.shutdown();
// do what you need to do here
}
}
像这样的东西
答案 2 :(得分:1)
好吧,如果你调用executorService.invokeAll(myListOfCallableTasks)和他们的executorService.shutDown()调用的线程将阻塞,直到完成所有任务: