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