0
点赞
收藏
分享

微信扫一扫

【设计模式】工厂方法模式——工厂方法模式在JDK源码中的应用

工厂方法模式在JDK源码中有很多应用场景,不仅有简单工厂模式,还有多工厂模式。


Executors

尽管ThreadPoolExecutor及其子类都是可以直接new出来的,但Executors还是提供了生产常用ThreadPoolExecutor实例的简单工厂:

public class Executors {

    /**
     * Creates a thread pool that reuses a fixed number of threads
     */
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
    }

    /**
     * Creates an Executor that uses a single worker thread operating
     */
    public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>(),
                                    threadFactory));
    }

    /**
     * Creates a thread pool that creates new threads as needed, but
     */
    public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>(),
                                      threadFactory);
    }

    /**
     * The default thread factory.
     */
    private static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

    /** Cannot instantiate. */
    private Executors() {}
}

可以看到newFixedThreadPool()是用来生产适合CPU密集场景的定长线程池的工厂方法、newCachedThreadPool()是用来生产适合IO密集场景的可缓存线程池的工厂方法、newSingleThreadExecutor()则是用来生产单线程模型下偶尔需要异步操作的单线程线程池的工厂方法(在Android场景下被IntentService代替),这是典型的简单工厂模式。

Executors的代码里用到了简单工厂模式,是否也用到了多工厂模式呢?答案是肯定的,注意静态内部类DefaultThreadFactory的父类ThreadFactory,就是典型的多工厂模式。


ThreadFactory

ThreadFactory用来生成Thread的实例,代码如下:

public interface ThreadFactory {
    Thread newThread(Runnable r);
}

可见ThreadFactory是仅有一个方法的接口,具体实现都是子类做的,除了上文提到的Executors.DefaultThreadFactory以外,还有CompletableFuture.Delayer.DaemonThreadFactory、CleanerImpl.InnocuousThreadFactory和Android的NamedThreadFactory等子类。




举报

相关推荐

0 条评论