执行器框架
Executor
Executor 是线程池类及很多执行器框架的最顶层接口
public interface Executor {
/**
* 在将来的某个时刻执行传入的 Runnable. The command
* 任务可能在新的线程,或缓存的线程,或调用该函数的线程中执行
*/
void execute(Runnable command);
}
从源码中可以看出,该接口并没有对线程池的实现做出规定,仅仅抽象了线程池类如何执行 Runnable 任务的行为。
ExecutorService
ExecutorService接口是Executor的次一级接口,对 Executor 接口进行扩展,添加了一系列线程池服务相关的接口。
public interface ExecutorService extends Executor {
/**
* 关闭线程池,按顺序将已经提交的任务执行完,并不接受新的任务
* 已经关闭的线程池再次调用将没有影响.
*/
void shutdown();
/**
* 尝试停止所有正在执行的任务,停止处理等待任务,返回等待执行的任务
* 该方法不等待任务终止。
* 该方法通过 interrupt 方法中断线程,所有不响应中断的线程将可能永远不会终止
*/
List<Runnable> shutdownNow();
/**
* 判断是否关闭
*/
boolean isShutdown();
/**
* 在 shutdown 之后如果所有任务都执行完成,返回 true
* 只有 shutdown 或者 shutdownNow 方法被调用以后才有可能返回 true
*/
boolean isTerminated();
/**
* 阻塞知道所有任务都完成或者到达超时时间或者当前线程被中断
*/
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
/**
* 提交一个 Callable 任务,返回一个 Future
*/
<T> Future<T> submit(Callable<T> task);
/**
* 提交一个 Runnable 任务,和 result 接收返回值
*/
<T> Future<T> submit(Runnable task, T result);
/**
* 提交一个 Runnable 任务并返回 Future
*/
Future<?> submit(Runnable task);
/**
* 提交一组 Callable 任务并返回对应的一组 Future
*/
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
/**
* 执行一组 Callable 任务,当所有任务完成或者超时时,返回已完成的任务的 Future
*/
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
/**
* 提交一组 Callable 任务,等待其中任何一个执行完成后返回
*/
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
/**
* 提交一组 Callable 任务,等待其中任何一个执行完成或到达等待时间后返回
*/
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
从代码中可以看出,ExecutorService
接口扩展了 Executor
接口,提供了一系列任务和执行器对象管理的接口。
对于该如何实现 ExecutorService,JDK中有很多值得学习和借鉴的设计,
很多框架中对于复杂接口的实现往往会运用模板方法设计模式,
用抽象类对一类执行器类型的公用方法进行实现,然后由继承者实现核心接口,著名的 AQS 框架也运用了这种设计模式。
AbstractExecutorService
AbstractExecutorService
抽象类继承并实现了ExecutorService
中的执行器类型的公用方法,代码如下:
/**
* 提供一个 ExecutorService 的默认实现
*/
public abstract class AbstractExecutorService implements ExecutorService {
/**
* 将 Runnable 任务封装为 RunnableFuture, 结果写入 value
*/
protected <T> RunnableFuture<T> newTaskFor