Executors:位于jav.util.concurrent包下,是Executor框架的线程工厂,通过Executors可以创建特定功能的线程池。其所创建的线程池主要有四类:newCachedThreadPool、newFixedThreadPool、newScheduledThreadPool、newSingleThreadExecutor。
newCachedThreadPool:可缓存线程池。该线程池没有最大线程数量的限制,可根据实际情况调整线程个数。当有任务时创建一个线程,线程在任务执行完(即空闲状态)60s后自动回收。Executors创建该线程池的方式为:
Executors.newCachedThreadPool();
/*public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}*/
newFixedThreadPool:定长线程池。该线程池有固定数量的线程且数量不变,当有任务提交时,若存在空闲线程则立即执行该任务,否则将任务存入一个任务队列中,知道线程池中出现空闲线程。Executors创建该线程池的方式为:
Executors.newFixedThreadPool(int Threads);
/* public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}*/
newSingleThreadExecutor:单线程化的线程池。只有一个线程的线程池,当一个任务提交后,若线程空闲则执行,否则将任务存于任务队列中。Executors创建该线程池的方式为:
Executors.newSingleThreadExecutor();
/* public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}*/
newScheduledThreadPool:定长线程池,支持定时及周期性任务执行。Executors创建该线程池的方式为:
Executors.newScheduledThreadPool(int corePoolSize);
/*public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
public class ScheduledThreadPoolExecutor
extends ThreadPoolExecutor
implements ScheduledExecutorService {...}*/
由上面几段代码可以看出:不论创建哪一种线程池,都离不开ThreadPoolExecutor。通过ThreadPoolExecutor,可以自定义线程池。其构造函数为:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) { }
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler){ }
其构造函数的参数:corePoolSize(核心线程数,只要线程池被实例化出来就恒定)、maximumPoolSize(线程池里线程的最大容量)、keepAliveTime(线程空闲状态下的销毁时间,long 表示数值)、unit(线程空闲状态下的销毁时间,TimeUnit 表示单位)、BlockingQueue<Runnable> workQueue、RejectedExecutionHandler handler(提交的任务在占用完所有的线程加装满了任务队列后剩下的任务的处理策略)。
根据传入的参数,ThreadPoolExecutor构建出newCachedThreadPool、newFixedThreadPool、newSingleThreadExecutor或者newScheduledThreadPool。