欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

深入了解Executors.newFixedThreadPool源码解析

程序员文章站 2022-09-28 16:56:33
Executors 有个常用静态方法newFixedThreadPool(int nThreads),来构造线程池 今天我们其源码实现,探一探究竟。 //new LinkedBlock...

Executors 有个常用静态方法newFixedThreadPool(int nThreads),来构造线程池
今天我们其源码实现,探一探究竟。

//new LinkedBlockingQueue()这里可以看出 是声明的*队列大小,默认大小为Integer.MAX_VALUE
   public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue());
    }

点进去看其实现。

corePoolSize、maximumPoolSize 两个值设置为一样,keepAliveTime为空闲线程存活时间,when the number of threads is greater than the core,这里该值为0。

//Executors.defaultThreadFactory() 用来构造线程的 Returns a default thread factory used to create new threads.
//defaultHandler: the default rejected execution handler,
//A handler for rejected tasks that throws a RejectedExecutionException 当 Runnable task处理不过来时会派上用场。

//private static final RejectedExecutionHandler defaultHandler = new AbortPolicy();

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }
再看下一步调用。
 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

至此调用完成。

总结:

newFixedThreadPool 提供一种快速构造线程池的接口,里面设置了很多默认参数,最终还是调用
ThreadPoolExecutor来构造 ExecutorService,ThreadPoolExecutor本身是
ExecutorService接口类的实现类。

当默认参数不满足需要是,直接 使用 ThreadPoolExecutor进行构造线程池。