在 Java 线程池中的每个工作线程上调用自定义关闭方法的优雅方法是什么?
假设我正在使用一个
ExecutorService ex = Executors.newFixedThreadPool(nrofthreads);
旋转一些工作并等待它完成。
但是,我在工作线程中有相同的 Threadlocal 对象,批处理完成后需要关闭这些对象。 因此,我希望能够对线程池创建的所有工作线程调用自定义关闭方法。
最优雅的方法是什么?
现在我正在使用的黑客:
for(int i =0 ; i<20; i++){ //make sure to touch all threads with 20 runs..
ex.execute(new Runnable(){
public void run(){
tearDownThreadLocals();
}
});
}
ex.shutdown();
但这对我来说看起来不是特别强大;-)
谢谢 国杰
say I'm using a
ExecutorService ex = Executors.newFixedThreadPool(nrofthreads);
spinning up some work and waiting when it's done.
However I have same Threadlocal objects in the worker-threads which need to be closed when the batch is done.
Therefore, I would like to be able to call a custom close-method on all worker-threads created by the threadpool.
What would be the most elegant way to do that?
Right now as a hack I'm using:
for(int i =0 ; i<20; i++){ //make sure to touch all threads with 20 runs..
ex.execute(new Runnable(){
public void run(){
tearDownThreadLocals();
}
});
}
ex.shutdown();
but that doesn't look particulary robust to me ;-)
Thanks
GJ
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 Executors.newFixedThreadPool(int, ThreadFactory) 来传递 ThreadFactory,如下所示:
编辑:刚刚注意到 Executors 已经有一个接受
ThreadFactory
的方法,因此不需要显式创建ThreadPoolExecutor
。You can use
Executors.newFixedThreadPool(int, ThreadFactory)
to pass aThreadFactory
, something like this:EDIT: Just noticed that
Executors
already has a method that accepts aThreadFactory
, so no need to createThreadPoolExecutor
explicitly.