一、引言
Java的线程既是工作单元,也是执行机制。
我们需要把这两者分开,让工作单元包括Runnable和Callable,而执行机制由Executor框架提供。
二、Executor框架
组成部分

- 任务。包括被执行任务需要实现的接口:Runnable接口或Callable接口
- 任务的执行。包括任务执行机制的核心接口Executor,以及继承自Executor的ExecutorService接口。Executor框架有两个关键类实现了ExecutorService接口(ThreadPoolExecutor和ScheduledThreadPoolExecutor)。
- 异步计算的结果。包括接口Future和实现Future接口的FutureTask类。
三、Executor类图

- Executor 执行器接口,该接口定义执行Runnable任务的方式,无返回值。
- ExecutorService 该接口定义提供对Executor的服务,对Executor做了一些扩展,主要增加了关闭线程池、执行有返回值任务、批量执行任务的方法。
- ScheduledExecutorService 定时调度接口。
- AbstractExecutorService 执行框架抽象类,运用模板方法设计模式实现了一部分方法,主要为执行有返回值任务、批量执行任务的方法。
- ThreadPoolExecutor JDK中线程池的具体实现。
- Executors 线程池工厂类
四、ThreadPoolExecutor
Executors可以创建不同类型线程池
FixedThreadPool:
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
它使用LinkedBlockingQueue队列,队列的容量为Integer.MAX_VALUE,所以maximumPoolSize,keepAliveTime是无效参数,在线程池达到核心线程数量后,任务都会进入队列,不会触发拒绝策略
应用场景:FixedThreadPool适用于为了满足资源管理的需求,而需要限制当前线程数量的应用场景,它适用于负载比较重的服务器。
SingleThreadExecutor:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
同样使用LinkedBlockingQueue,不过使用单个worker线程的Executor,核心线程和最大线程都是1,其它和FixedThreadPool一样
应用场景:SingleThreadExecutor适用于需要保证顺序地执行各个任务;并且在任意时间点,不会有多个线程是活动的应用场景
CachedThreadPool:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
corePoolSize为0,maximumPool为Integer.MAX_VALUE,也就是说极端情况下会一直创建新的线程。使用没有容量的SynchronousQueue作为线程池的工作队列。keepAliveTime设置为60L,意味着CachedThreadPool中的空闲线程等待新任务的最长时间为60秒,空闲线程超过60秒后终止。
应用场景:CachedThreadPool是大小无界的线程池,适用于执行很多的短期异步任务的小程序,或者
是负载较轻的服务器。
ScheduledThreadPool
ScheduledThreadPoolExecutor 继承ThreadPoolExecutor且实现了ScheduledExecutorService接口,它就相当于提供了“延迟”和“周期执行”功能的ThreadPoolExecutor,这个线程池可以实现任务的延迟和周期性调度,在另一篇文章中有详细介绍。