线程终止时的Java ExecutorService回调

时间:2011-05-02 21:26:40

标签: java multithreading threadpool executorservice

我使用缓存线程池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

谢谢,

Shreyas

1 个答案:

答案 0 :(得分:14)

在您的ThreadFactory代码中,创建Thread的实例,以便try执行为其创建的Runnable的工作,然后{{1}做你的清理工作。像这样:

finally
相关问题