Executors是一个线程池的工具类,方便我们创建各种各样的线程池。
对于我们常用的线程池ThreadExecutorPool,提供了四种工厂方法。
先回顾下ThreadExecutorPool构造函数吧:
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;
}
1.newFixedThreadPool:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
该方法构造了一个固定大小的线程池,设置了corePoolSize=maxPoolSize,来实现固定大小。另外指定了queue为LinkedBlockQueue类型,等价于一个无界队列,即queue可以无限存放任务。另外这些线程由于是核心线程,所以不会消亡。
public LinkedBlockingQueue() {
this(Integer.MAX_VALUE);
}
2.newCachedThreadPool:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
该方法构造了一个可重用线程的线程池,意味着,如果没有可用的线程,则新建线程。线程执行完任务空闲时会缓存60s,如果没有新的任务则销毁。所以该线程池在空闲状态下没有worker线程的开销。但是该线程池在有任务的状态下,线程池数目不可控。
3.newSingleThreadExecutor:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
该方法构造了一个单线程的线程池。可以认为是fixedThreadPool的特例。
4.newScheduledThreadPool:
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
该方法仅仅返回了一个具有corePoolSize数目线程的周期性线程池。构造完毕后,可以调用其各种schedule方法达到周期性执行任务的需求。具体见ScheduledExecutorService接口。