目录
Executor框架
Java中也有一套框架来控制管理线程,那就是Executor框架。Executor框架是JDK1.5之后才引入的,位于java.util.cocurrent 包下,可以通过该框架来控制线程的启动、执行和关闭,从而简化并发编程的操作,这是它的核心成员类图:

Executor:最上层的接口,定义了一个基本方法execute,接受一个Runnable参数,用来替代通常创建或启动线程的方法。
ExecutorService:继承自Executor接口,提供了处理多线程的方法。
ScheduledExecutorService:定时调度接口,继承自ExecutorService。
AbstractExecutorService:执行框架的抽象类。
ThreadPoolExecutor:线程池中最核心的一个类,提供了线程池操作的基本方法。
Executors:线程池工厂类,可用于创建一系列有特定功能的线程池。
ThreadPoolExecutor详解
以上Executor框架中的基本成员,其中最核心的的成员无疑就是ThreadPoolExecutor,想了解Java中线程池的运行机制,就必须先了解这个类,而最好的了解方式无疑就是看源码。
构造函数
打开ThreadPoolExecutor的源码,发现类中提供了四个构造方法
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); } public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, defaultHandler); } public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler); } 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; }可以看出,ThreadPoolExecutor的构造函数中的参数还是比较多的,并且最核心的是第四个构造函数,其中完成了底层的初始化工作。
下面解释一下构造函数参数的含义:
- corePoolSize:线程池的基本大小。当提交一个任务到线程池后,线程池会创建一个线程执行任务,重复这种操作,直到线程池中的数目达到corePoolSize后不再创建新线程,而是把任务放到缓存队列中。
- maximumPoolSize:线程池允许创建的最大线程数。
- workQueue:阻塞队列,用于存储等待执行的任务,并且只能存储调用
execute方法提交的任务。常用的有三种队列,SynchronousQueue,LinkedBlockingDeque,ArrayBlockingQueue。 - keepAliveTime:线程池中线程的最大空闲时间,这种情况一般是线程数目大于任务的数量导致。
- unit:keepAliveTime的时间单位,TimeUnit是一个枚举类型,位于java.util.concurrent包下。
-
threadFactory:线程工厂,用于创建线程。
-
handler:拒绝策略,当任务太多来不及处理时所采用的处理策略。
重要的变量
看完了构造函数,我们来看下ThreadPoolExecutor类中几个重要的成员变量:
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0)); private static
