在 Java 线程池中的每个工作线程上调用自定义关闭方法的优雅方法是什么?

发布于 2024-08-24 04:01:58 字数 505 浏览 6 评论 0原文

假设我正在使用一个

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

她说她爱他 2024-08-31 04:01:58

您可以使用 Executors.newFixedThreadPool(int, ThreadFactory) 来传递 ThreadFactory,如下所示:

ExecutorService ex = Executors.newFixedThreadPool(nrofthreads, 
    new ThreadFactory() {
        public Thread newThread(final Runnable r) {
            return new Thread(new Runnable() {
                public void run() {
                    try {
                        r.run();
                    } finally {
                        tearDownThreadLocals();
                    }
                }
            });
        }
    });

编辑:刚刚注意到 Executors 已经有一个接受 ThreadFactory 的方法,因此不需要显式创建 ThreadPoolExecutor

You can use Executors.newFixedThreadPool(int, ThreadFactory) to pass a ThreadFactory, something like this:

ExecutorService ex = Executors.newFixedThreadPool(nrofthreads, 
    new ThreadFactory() {
        public Thread newThread(final Runnable r) {
            return new Thread(new Runnable() {
                public void run() {
                    try {
                        r.run();
                    } finally {
                        tearDownThreadLocals();
                    }
                }
            });
        }
    });

EDIT: Just noticed that Executors already has a method that accepts a ThreadFactory, so no need to create ThreadPoolExecutor explicitly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文