Shr*_*nde 13 java multithreading executorservice threadpool
我使用缓存线程池ExecutorService来运行一些异步后台任务.我已经提供了我的ThreadFactory,它将线程分发给ExecutorService(只要它需要它们).我对缓存线程池的理解是,在线程空闲60秒后,它由ExecutorService终止.
当我的线程即将被终止时,我想执行一些状态清理.实现这一目标的最佳方法是什么?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
Run Code Online (Sandbox Code Playgroud)
谢谢,
Shreyas
Tim*_*der 14
在您的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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8662 次 |
最近记录: |