【问题标题】:Control Over Termination Threads in Java Executor-framework在 Java Executor-framework 中控制终止线程
【发布时间】:2014-05-09 05:58:28
【问题描述】:

注意:我是英文新手,如有错误请见谅。

我使用线程本地来保存每个线程的资源;并在某些任务中使用它(线程本地)。我通过 java executor-service 运行我的任务。当线程要终止时,我会关闭我的资源;然后我需要在我调用“executor.shoutdown”方法之后,通过 executor-service 在所有创建的线程中运行一个任务。我如何强制执行程序在每个线程中运行一个任务,什么时候会终止这些任务?

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

}

【问题讨论】:

    标签: java multithreading executorservice thread-local


    【解决方案1】:

    大多数执行器都可以用 ThreadFactory 构建。 ForkJoinPool 也是如此。但是,为了简单起见,我使用了不同的 ExecutorService

    ExecutorService executor = Executors.newFixedThreadPool(
        10, new FinalizerThreadFactory(Executors.defaultThreadFactory()));
    

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

    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.
                    }
                }
            });
        }
    }
    

    【讨论】:

    • 我为forkjoinpool写代码:gist;感谢@nosid
    猜你喜欢
    • 2015-12-21
    • 2014-11-18
    • 2012-08-28
    • 1970-01-01
    • 2014-11-01
    • 2011-08-11
    • 1970-01-01
    • 2023-03-28
    • 2021-04-05
    相关资源
    最近更新 更多