第一部分:ThreadPoolExecutor的继承结构
根据上图可以知道,ThreadPoolExecutor是继承的AbstractExecutorService(抽象类)。再来看一下AbstractExecutorService的结构可以发现,AbstractExecutorService实现了ExecutorService,并且ExecutorService继承Executor接口。
如下是Executor和ExecutorService接口中一些方法:
public interface Executor {
void execute(Runnable command);
}
public interface ExecutorService extends Executor {
void shutdown();
List<Runnable> shutdownNow();
boolean isShutdown();
boolean isTerminated();
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
可以简单总结一下:Executor这个接口只有一个方法execute(Runnable command)(以Command Pattern(命令模式)的设计模式实现);在ExecutorService接口中一部分是和执行器生命周期相关的方法,而另一部分则是以各种方式提交要执行的任务的方法。像submit()就是提交任务的一个方法,在实现中做了适配的工作,无论参数是Runnable还是Callable,执行器都会正确执行。ExecutorService中,和生命周期相关的,声明了5个方法:
- awaitTermination() 阻塞等待shutdown请求后所有线程终止,会有时间参数,超时和中断也会令方法调用结束
- isShutdown() 通过ctl属性判断当前的状态是否不是RUNNING状态
- isTerminated() 通过ctl属性判断当前的状态是否为TERMINATED状态
- shutdown() 关闭Executor,不再接受提交任务
- shutdownNow() 关闭Executor,不再接受提交任务,并且不再执行入队列中的任务
可以看出来:AbstractExecutorService这个类是ExecutorService的一个抽象实现。其中,提交任务的各类方法已经给出了十分完整的实现。之所以抽象,是因为和执行器本身生命周期相关的方法在此类中并未给出任何实现,需要子类扩展完善(模板方法设计模式)拿一个submit方法出来分析一下:
/**
* @throws RejectedExecutionException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
从代码可以看出实际上用到的是RunnableFuture的实现类FutureTask。但最终还是调用了execute()方法,在子类中实现。
在正式进入ThreadPoolExecutor源码分析之前还需要补充一点的是:Executors(工厂方法设计模式)java.util.concurrent.Executors是个工具类,提供了很多静态的工具方法。其中很多对于执行器来说就是初始化构建用的工厂方法。
- 重载实现的newFixedThreadPool()
- 重载实现的newSingleThreadExecutor()
- 重载实现的newCachedThreadPool()
- 重载实现的newSingleThreadScheduledExecutor()
- 重载实现的newScheduledThreadPool()
这些方法返回的ExecutorService对象最终都是由ThreadPoolExecutor实现的,根据不同的需求以不同的参数配置,或经过其它类包装。其中,Executors中的一些内部类就是用来做包装用的。Executors类中还有静态的defaultThreadFactory()方法,当然也可以自己实现自定义的ThreadFactory。
第二部分:ThreadPoolExecutor源码分析
下面正式进入ThreadPoolExecutor:(按照程序运行顺序分析)
1、ThreadPoolExecutor的全参数构造方法:
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPool