[英]Java ExecutorService callback on thread terminate
我正在使用缓存线程池 ExecutorService 来运行一些异步后台任务。 我已经提供了我的 ThreadFactory,它将线程分发给 ExecutorService(只要它需要它们)。 我对缓存线程池的理解是,在线程空闲 60 秒后,它会被 ExecutorService 终止。
当我的线程即将终止时,我想执行一些 state 清理。 实现这一目标的最佳方法是什么? ExecutorService 不会轻易地提供进入线程生命周期的钩子。
我不想关闭我的 ExecutorService - 这对于在任务到来时运行任务很有用。
ExecutorService executor = Executors.newCachedThreadPool(new MyThreadFactory());
// Do some work
executor.submit(new MyCallable());
// Need a way for the ExecutorService to notify me when it is about to
// terminate my thread - need to perform some cleanup
谢谢,
什雷亚斯
在您的ThreadFactory
代码中,创建Thread
的实例,以便它try
完成为其创建的Runnable
的工作,然后finally
完成您的清理工作。 像这样:
public Thread newThread(final Runnable r) {
Thread t = new Thread() {
public void run() {
try {
r.run();
} finally {
//do cleanup code
}
}
};
return t;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.