线程池构造函数与参数列表
面试时候问到了关于线程池的构造函数参数列表的问题,下面进行一些总结:
一、线程池种类
- FixedThreadPool
- CachedThreadPool
- ScheduledThreadPool
1. FixedThreadPool
FixedThreadPool, 就是创建有固定线程数量的线程池,来看Executors 静态创建方法:
/**
* 创建有固定线程数量的线程池
@param nThreads, 初始化线程大小
*/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
/**
初始化固定大小线程池
@param nThreads 线程池大小
@param threadFactory 线程工厂
*/
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
其中参数int nThreads 代表初始化数量,threadFactory是创建工厂, 返回的是ThreadPoolExecutor
代码如下:
// Public constructors and methods
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters and default thread factory and rejected execution handler.
* It may be more convenient to use one of the {@link Executors} factory
* methods instead of this general purpose constructor.
*
* @param corePoolSize 初始化线程池大小
*
* @param maximumPoolSize 允许的最大线程数
* @param keepAliveTime 最大活跃时间, 当空闲超过这个时间后就会被关闭.
* @param unit 时间单位
* @param workQueue 持有等待执行线程的队列
*
* @throws IllegalArgumentException 当发生如下一个情况,就抛出该异常
* {@code corePoolSize < 0}
* {@code keepAliveTime < 0}
* {@code maximumPoolSize <= 0}
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
CachedThreadPool
先看构造函数
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
最大线程数是Integer.MAX_VALUE, 一个无参构造,一个有参构造,ThreadFactory
SceduledThradPool
构造函数:
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
corePoolSize 参数, 和thredFactory