Executors 有个常用静态方法newFixedThreadPool(int nThreads),来构造线程池
今天我们其源码实现,探一探究竟
//new LinkedBlockingQueue<Runnable>()这里可以看出 是声明的无界队列大小,默认大小为Integer.MAX_VALUE
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
点进去看其实现
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<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
再看下一步调用
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> 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进行构造线程池