一文看懂Concurrent面试常问类Executor,ExecutorService,AbstractExecutorService,ThreadPoolExecutor作用,关系与区别

Concurrent包是jdk1.5所提供的一个针对高并发进行编程的包,也是多线程并发编程最喜欢问的,特别是从线程,线程池的使用做为最简单的切入点,先看个不太好理解的类图

在这里插入图片描述

接下来我们从头往下,一步步拆分开来研究:

在这里插入图片描述

Executor:多线程框架的主要接口,它底层就是一个execute执行方法。它代表着线程任务的执行,也是一切的开始,不管什么线程安全策略,多线程管理,定时,串行执行,都是建立在这个“执行”的基础之上,没有execute执行,线程也就等于无用。看它源码注释:

An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use:
Executor executor = anExecutor;
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());

以前我们学多线程的时候,记不记得有种写法就是这样直接new Runnable多线程任务,但是这种线程创建方式是不规范,不安全的。
The Executor implementations provided in this package implement ExecutorService, which is a more extensive interface. The ThreadPoolExecutor class provides an extensible thread pool implementation. The Executors class provides convenient factory methods for these Executors.
Memory consistency effects: Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread.
在这里插入图片描述
ExecutorService是实现Executor接口的拥有更多扩展方法的一个接口。而ThreadPoolExecutor类提供了可扩展的线程池实现方式,Executors类则是为那些多线程的执行提供了便利的工厂模式(这一段话你就当它开始介绍它的儿子们多么有出息,下面会详细介绍)

ExecutorService:上面Executor就是它的父亲,注释里也介绍过它,它拥有更多的扩展方法,功能更强大,按照惯例,我们也是先看看它的自我介绍注释

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.
An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown method will allow previously submitted tasks to execute before terminating, while the shutdownNow method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.
Method submit extends ba

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值