Executor框架的两级调度模型(基于HotSpot)Executor框架)将这些任务映射为固定数量的线程;任务的两级调度模型
结构
Runnable接口或Callable接口。Executor,以及继承自Executor的ExecutorService接口。Executor框架有两个关键类实现了ExecutorService接口(ThreadPoolExecutor和ScheduledThreadPoolExecutor)。Future和实现Future接口的FutureTask类。类与接口
成员
ThreadPoolExecutor:通常使用工厂类Executors来创建。
SingleThreadExecutor
需要保证顺序地执行各个任务;并且在任意时间点,不会有多个线程是活动的应用场景。FixedThreadPool
负载比较重的服务器。CachedThreadPool
执行很多的短期异步任务的小程序,或者是负载较轻的服务器。ScheduledThreadPoolExecutor:通常使用工厂类Executors来创建.
Future接口
Runnable接口和Callable接口
Runnable不会返回结果。Callable可以返回结果。ThreadPoolExecutor详解
4个组件
corePool:核心线程池的大小。maximumPool:最大线程池的大小。BlockingQueue:用来暂时保存任务的工作队列。RejectedExecutionHandler:当ThreadPoolExecutor已经关闭或ThreadPoolExecutor已经饱和时(达到了最大线程池大小且工作队列已满),execute()方法将要调用的Handler。3种ThreadPoolExecutor
FixedThreadPool
LinkedBlockingQueue作为线程池的工作队列(队列的容量为Integer.MAX_VALUE。SingleThreadExecutor
worker线程的Executor。LinkedBlockingQueue作为线程池的工作队列(队列的容量为Integer.MAX_VALUE。CachedThreadPool
ScheduledThreadPoolExecutor详解
ScheduledThreadPoolExecutor 运行机制图
Java里的阻塞队列
ArrayBlockingQueue:数组有界阻塞队列,默认线程非公平的访问队列,公平性是使用可重入锁实现
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
原文:https://www.cnblogs.com/lycsmzl/p/13213567.html