那些年向前冲|Java线程池深度揭秘
作为 Java 程序员 , 无论是技术面试、项目研发或者是学习框架源码 , 不彻底掌握 Java 多线程的知识 , 做不到心中有数 , 干啥都没底气 , 尤其是技术深究时往往略显发憷 。
坐稳扶好 , 通过今天的分享 , 能让你轻松 get 如下几点 。
1. Executor 框架家族简介;
2. 源码解读:线程池状态以及状态流转;
3. 源码解读:部分成员变量及方法;
4. 源码解读:任务提交submit方法背后;
5. 源码揭秘之后的反思;
6. 寄语 。
Executor 家族简介一图胜千言 , 脑中有图心不慌 。
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();RunnableFutureAbstractExecutorService 是一个抽象类 , 实现了 ExecutorService 接口中的部分方法 , 例如提供了任务提交的 submit 方法的默认实现 , 而 submit 方法最终会调用 execute 方法 。
不过 AbstractExecutorService 并没有实现 execute 方法 , 相当于为子类留了个口子 , 让子类去灵活扩展(钩子函数) 。
(四)ScheduledExecutorService 接口 。
public interface ScheduledExecutorService extends ExecutorService {public ScheduledFuture> schedule(Runnable command, long delay, TimeUnit unit);public ScheduledExecutorService 接口继承了 ExecutorService , 增加定时调度的方法 , 使其成为一个可定时调度任务的接口 , 相当于扩展了 ExecutorService 的功能 。
推荐阅读
- 小机灵鬼|干货速来!透彻剖析微服务架构设计模式,深入开发Java有奇效
- 罗云熙|盘点那些古装帅,现代装却很“丑”的3位男神,罗云熙任嘉伦上榜
- 大众报业·海报新闻|盘点那些低价转让的公司,长城宽带100万元打包转让
- Java|计算机专业的本科生,该选择学习Java技术体系还是.NET技术体系
- 【】长城宽带100万元打包转让 盘点那些低价转让的公司
- 时尚广州|T恤的标语你了解过吗?揭秘衣服上那些奇怪的字句
- 刘药师话用药|有一种健康和美丽,从脚下开始,足部护理那些事儿
- 穿搭日记|那些一眼就让人爱上的明星耳环,便宜的才几百,陈小纭金晨都在戴
- 穿搭|那些乘风破浪的姐姐们,为什么每次都能把职业装穿得美出圈?
- 穿搭■为什么气质上总是输一大截?来看看那些教科书式的穿搭吧,学起来
