那些年向前冲|Java线程池深度揭秘

作为 Java 程序员 , 无论是技术面试、项目研发或者是学习框架源码 , 不彻底掌握 Java 多线程的知识 , 做不到心中有数 , 干啥都没底气 , 尤其是技术深究时往往略显发憷 。
坐稳扶好 , 通过今天的分享 , 能让你轻松 get 如下几点 。
1. Executor 框架家族简介;
2. 源码解读:线程池状态以及状态流转;
3. 源码解读:部分成员变量及方法;
4. 源码解读:任务提交submit方法背后;
5. 源码揭秘之后的反思;
6. 寄语 。
Executor 家族简介一图胜千言 , 脑中有图心不慌 。
那些年向前冲|Java线程池深度揭秘executor 家族简图
(一)Executor 接口 。
public interface Executor {void execute(Runnable command);}Executor 是一个接口(主要用于定义规范) , 定义了 execute 方法 , 用于接收 Runnable 对象 。
(二)ExecutorService 接口 。
public interface ExecutorService extends Executor {// ... ...Future submit(Callable task);Future submit(Runnable task, T result);Future submit(Runnable task);// ... ...}ExecutorService 也是一个接口 , 继承了 Executor 接口 , 增加了更多方法 , 相当于扩展了 Executor 接口的功能 , 例如定义了 submit() 系列方法 , 支持任务执行后得到返回结果 。
(三)AbstractExecutorService 抽象类 。
public abstract class AbstractExecutorService implements ExecutorService {// ... ...protectedRunnableFuture newTaskFor(Runnable runnable, T value) {return new FutureTask(runnable, value);}protectedRunnableFuture newTaskFor(Callable callable) {return new FutureTask(callable);}public Future submit(Runnable task) {if (task == null) throw new NullPointerException();RunnableFuture ftask = newTaskFor(task, null);execute(ftask);return ftask;}publicFuture submit(Runnable task, T result) {if (task == null) throw new NullPointerException();RunnableFuture ftask = newTaskFor(task, result);execute(ftask);return ftask;}publicFuture submit(Callable task) {if (task == null) throw new NullPointerException();RunnableFuture ftask = newTaskFor(task);execute(ftask);return ftask;}// ... ...}AbstractExecutorService 是一个抽象类 , 实现了 ExecutorService 接口中的部分方法 , 例如提供了任务提交的 submit 方法的默认实现 , 而 submit 方法最终会调用 execute 方法 。
不过 AbstractExecutorService 并没有实现 execute 方法 , 相当于为子类留了个口子 , 让子类去灵活扩展(钩子函数) 。
(四)ScheduledExecutorService 接口 。
public interface ScheduledExecutorService extends ExecutorService {public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit);public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit);public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);}ScheduledExecutorService 接口继承了 ExecutorService , 增加定时调度的方法 , 使其成为一个可定时调度任务的接口 , 相当于扩展了 ExecutorService 的功能 。


推荐阅读