简介
JAVA 线程的创建和销毁需要一定的系统开销,Java的线程即是工作单元,也是执行机制,JDK5开始工作单元和执行机制分离开来,工作单元包括Runnable和Callable,而执行机制有Executor框架提供
两级调度模型
应用程序通过Executor框架控制上层的调度;而下层的调度由操作系统内核控制,下层的调度不受应用程序的控制
3大部分组成
任务
包括被执行任务需要实现的接口:Runnable接口或Callable接口任务的执行
包括任务执行的核心接口Executor,以及继承自Executor的ExecutorService接口(Executor框架有两个关键类实现了ExecutorService接口
(ThreadPoolExecutor和ScheduledThreadPoolExecutor)异步计算的结果
包括接口Future和实现Future接口的FutureTask类
2.类和接口的简介
- Executor是一个接口,它是Executor框架的基础,它将任务的提交与任务的执行分离开来。
- ThreadPoolExecutor是线程池的核心实现类,用来执行被提交的任务。
- ScheduledThreadPoolExecutor是一个实现类,可以在给定的延迟后运行命令,或者定期执行命令。ScheduledThreadPoolExecutor比Timer更灵活,功能更强大
- Future接口和实现Future接口的FutureTask类,代表异步计算的结果。
- Runnable接口和Callable接口的实现类,都可以被ThreadPoolExecutor或Scheduled-ThreadPoolExecutor执行。
Executor框架的成员
ThreadPoolExecutor
- ThreadPoolExecutor通常使用工厂类Executors来创建。Executors可以创建3种类型的
- ThreadPoolExecutor:SingleThreadExecutor、FixedThreadPool和CachedThreadPool
下面是Executors提供的,创建使用固定线程数的FixedThreadPool的
API。
public static ExecutorService newFixedThreadPool(int nThreads)
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactorythreadFact
FixedThreadPool适用于为了满足资源管理的需求,而需要限制当前线程数量的应用场景,它适用于负载比较重的服务器。
SingleThreadExecutor
下面是Executors提供的,创建使用单个线程的SingleThread-Executor的API。
public static ExecutorService newSingleThreadExecutor()
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory)
SingleThreadExecutor适用于需要保证顺序地执行各个任务;并且在任意时间点,不会有多个线程是活动的应用场景。
CachedThreadPool
下面是Executors提供的,创建一个会根据需要创建新线程的CachedThreadPool的API。
public static ExecutorService newCachedThreadPool()
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory)
CachedThreadPool是大小无界的线程池,适用于执行很多的短期异步任务的小程序,或者是负载较轻的服务器。
ScheduledThreadPoolExecutor
- ScheduledThreadPoolExecutor。包含若干个线程的ScheduledThreadPoolExecutor。
- SingleThreadScheduledExecutor。只包含一个线程的ScheduledThreadPoolExecutor。
创建固定个数线程的ScheduledThreadPoolExecutor的API。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize,ThreadFactory
ScheduledThreadPoolExecutor适用于需要多个后台线程执行周期任务,同时为了满足资源
管理的需求而需要限制后台线程的数量的应用场景
创建单个线程的SingleThreadScheduledExecutor的API。
public static ScheduledExecutorService newSingleThreadScheduledExecutor()
public static ScheduledExecutorService newSingleThreadScheduledExecutor
(ThreadFactory threadFactory)
SingleThreadScheduledExecutor适用于需要单个后台线程执行周期任务,同时需要保证顺
序地执行各个任务的应用场景。
Future接口
Future接口和实现Future接口的FutureTask类用来表示异步计算的结果。当我们把Runnable
接口或Callable接口的实现类提交(submit)给ThreadPoolExecutor或
ScheduledThreadPoolExecutor时,ThreadPoolExecutor或ScheduledThreadPoolExecutor会向我们
返回一个FutureTask对象。下面是对应的API
<T> Future<T> submit(Callable<T> task)
<T> Future<T> submit(Runnable task, T result)
Future<> submit(Runnable task)
Runnable接口和Callable接口
Runnable接口和Callable接口的实现类,都可以被ThreadPoolExecutor或Scheduled-
ThreadPoolExecutor执行,它们之间的区别是Runnable不会返回结果,而Callable可以返回结
果。除了可以自己创建实现Callable接口的对象外,还可以使用工厂类Executors来把一个Runnable包装成一个Callable。
public static Callable<Object> callable(Runnable task) //假设返回对象Callable1
把一个Runnable和一个待返回的结果包装成一个Callable的API
public static <T> Callable<T> callable(Runnable task, T result) // 假设返回对象Callable2
FutureTask.get()将返回该任务的结果
ThreadPoolExecutor详解
Executor框架最核心的类是ThreadPoolExecutor,它是线程池的实现类,主要由下列4个组件构成。
- corePool:核心线程池的大小
- maximumPool:最大线程池的大小。
- BlockingQueue:用来暂时保存任务的工作队列。
- RejectedExecutionHandler:当ThreadPoolExecutor已经关闭或ThreadPoolExecutor已经饱和时(达到了最大线程池大小且工作队列已满),execute()方法将要调用的Handler。
- 通过Executor框架的工具类Executors,可以创建3种类型的ThreadPoolExecutor
- FixedThreadPool
- SingleThreadExecutor。
- CachedThreadPool。
FixedThreadPool被称为可重用固定线程数的线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
FixedThreadPool的corePoolSize和maximumPoolSize都被设置为创建FixedThreadPool时指
定的参数nThreads。
当线程池中的线程数大于corePoolSize时,keepAliveTime为多余的空闲线程等待新任务的
最长时间,超过这个时间后多余的线程将被终止。这里把keepAliveTime设置为0L,意味着多余
的空闲线程会被立即终止。
FixedThreadPool的execute()方法
- 如果当前运行的线程数少于corePoolSize,则创建新线程来执行任务。
- 在线程池完成预热之后(当前运行的线程数等于corePoolSize),将任务加入LinkedBlockingQueue。
- 线程执行完1中的任务后,会在循环中反复从LinkedBlockingQueue获取任务来执行。
- FixedThreadPool使用无界队列LinkedBlockingQueue作为线程池的工作队列(队列的容量为
Integer.MAX_VALUE)。使用无界队列作为工作队列会对线程池带来如下影响。 - 当线程池中的线程数达到corePoolSize后,新任务将在无界队列中等待,因此线程池中
的线程数不会超过corePoolSize。 - 由于1,使用无界队列时maximumPoolSize将是一个无效参数。
- 由于1和2,使用无界队列时keepAliveTime将是一个无效参数。
- 由于使用无界队列,运行中的FixedThreadPool(未执行方法shutdown()或
shutdownNow())不会拒绝任务(不会调用RejectedExecutionHandler.rejectedExecution方法)。
SingleThreadExecutor详解
SingleThreadExecutor是使用单个worker线程的Executor。下面是SingleThreadExecutor的源
代码实现。
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
- 如果当前运行的线程数少于corePoolSize(即线程池中无运行的线程),则创建一个新线
程来执行任务。 - 在线程池完成预热之后(当前线程池中有一个运行的线程),将任务加入Linked-
BlockingQueue。 - 线程执行完1中的任务后,会在一个无限循环中反复从LinkedBlockingQueue获取任务来执行。
CachedThreadPool详解
CachedThreadPool是一个会根据需要创建新线程的线程池。下面是创建CachedThread-
Pool的源代码。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
CachedThreadPool的corePoolSize被设置为0,即corePool为空;maximumPoolSize被设置为
Integer.MAX_VALUE,即maximumPool是无界的。这里把keepAliveTime设置为60L,意味着
CachedThreadPool中的空闲线程等待新任务的最长时间为60秒,空闲线程超过60秒后将会被
终止。
FixedThreadPool和SingleThreadExecutor使用无界队列LinkedBlockingQueue作为线程池的
工作队列。CachedThreadPool使用没有容量的SynchronousQueue作为线程池的工作队列,但
CachedThreadPool的maximumPool是无界的。这意味着,如果主线程提交任务的速度高于
maximumPool中线程处理任务的速度时,CachedThreadPool会不断创建新线程。极端情况下,
CachedThreadPool会因为创建过多线程而耗尽CPU和内存资源。
ScheduledThreadPoolExecutor详解
ScheduledThreadPoolExecutor继承自ThreadPoolExecutor。它主要用来在给定的延迟之后运
行任务,或者定期执行任务。ScheduledThreadPoolExecutor的功能与Timer类似,但
ScheduledThreadPoolExecutor功能更强大、更灵活。Timer对应的是单个后台线程,而
ScheduledThreadPoolExecutor可以在构造函数中指定多个对应的后台线程数。
- 本文链接: https://blog.zoozer.club/archives/e-x-e-c-u-t-o-r-kuang-jia
- 版权声明: 本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0 许可协议。转载请注明出处!