Executors是创建线程池的简便工具类,它帮我们提供了几种关于创建线程池的简便方法,如:
创建一个固定大小的线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
创建一个可以根据实际情况调整数量的线程池
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
创建一个只有一个线程的线程池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
可以从以上的几个方法中看出,它们都是对 ThreadPoolExecutor 的封装,下面来看看 ThreadPoolExecutor 的构造函数:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
函数的参数含义如下:
corePoolSize:指定了线程池中的线程数量;
maxImumPoolSize:指定了线程池中的最大线程数量;
keepAliveTime:当线程池的线程数量超过了 corePoolSize 时,多余的空闲线程的存活时间。即超过了 corePoolSize 的空闲线程&#