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