首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java Executor框架中终止线程的控制

Java Executor框架中终止线程的控制
EN

Stack Overflow用户
提问于 2014-05-09 05:58:28
回答 1查看 490关注 0票数 2

注:我是英语新手,所以请原谅我在英语中的任何错误。

我使用线程本地来保存每个线程的资源,并在一些任务中使用它(线程本地)。我通过java执行器服务运行我的任务。当线程终止时,我会关闭资源;然后,在调用"executor.shoutdown“方法之后,我需要在所有通过executor-service创建的线程中运行一个任务。我怎样才能强迫执行器在每个线程上运行一个任务,何时它会终止这些任务?

代码语言:javascript
复制
import java.util.concurrent.*;

public class Main2 {

    public static void main(String[] args) {

        ExecutorService executor = new ForkJoinPool(3);
        SimpleValue val = new SimpleValue();
        for(int i=0; i<1000; i++){
            executor.execute(new Task(val));
        }

        executor.shutdown();
        while( true ) {
            try {
                if( executor.awaitTermination(1, TimeUnit.SECONDS) ) System.exit(0);
            } catch(InterruptedException intrExc) {
                // continue...
            }
        }
    }

    protected static interface ResourceProvider<T>
    extends AutoCloseable {
        public T get();
        public ResourceProvider<T> reset() throws Exception;
        public ResourceProvider<T> reset(boolean force) throws Exception;
        public void close();
    }

    protected static abstract class ThreadLocalResourceProvider<T>
    extends ThreadLocal<T>
    implements ResourceProvider<T> {}

    protected static class SimpleValue
    extends ThreadLocalResourceProvider<String> {
        public String initialValue() {
            return "Hello " + Thread.currentThread().getName();
        }
        public SimpleValue reset() throws Exception {
            return reset(false);
        }
        public SimpleValue reset(boolean force) throws Exception{
            set(this.initialValue());
            return this;
        }
        public void close() {
            remove();
        }
    }

    protected static class Task
    implements Runnable {

        protected SimpleValue val;
        public Task(SimpleValue val) {
            this.val = val;
        }

        @Override
        public void run() {
            try {
                System.out.print(val.reset().get());
            } catch( Exception exc ) {
                System.out.print( exc.getMessage() );
            }
        }
    }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-09 07:13:25

大多数执行器都可以使用ThreadFactory构建。对于ForkJoinPool来说也是如此。但是,为了简化,我使用了不同的ExecutorService。

代码语言:javascript
复制
ExecutorService executor = Executors.newFixedThreadPool(
    10, new FinalizerThreadFactory(Executors.defaultThreadFactory()));

类FinalizerThreadFactory将线程的创建委托给传递的线程工厂。但是,它创建的线程将在退出之前执行一些额外的代码。这很简单:

代码语言:javascript
复制
class FinalizerThreadFactory implements ThreadFactory {
    private final ThreadFactory delegate;
    public FinalizerThreadFactory(ThreadFactory delegate) {
        this.delegate = delegate;
    }
    public Thread newThread(final Runnable r) {
        return delegate.newThread(new Runnable() {
            public void run() {
                try {
                    r.run();
                } finally {
                    // finalizer code goes here.
                }
            }
        });
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23557550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档