2

说我正在使用

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();

但这对我来说看起来并不特别强大;-)

谢谢GJ

4

1 回答 1

4

您可以使用Executors.newFixedThreadPool(int, ThreadFactory)传递 a 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已经有一个接受 a 的方法ThreadFactory,所以不需要ThreadPoolExecutor显式创建。

于 2010-03-05T11:03:28.473 回答