Executor框架的结构
- 任务:被执行的任务需要实现Runnable接口或Callable接口
- 任务的执行:ScheduledThreadPoolExecutor、ThreadPoolExecutor
- 异步计算的结果:Future、FutureTask
Executors
1)FixedThreadPool: 适用于为了满足资源管理需求,需要现在当前线程数量的应用场景,适用于负载较重的服务器.
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public LinkedBlockingQueue() {
this(Integer.MAX_VALUE);
}
输入的线程数就是核心线程数也是最大线程数,不存在空闲线程所以keepLiveTime是0,LinkedBlockingQueue没有指明长度,使用这种无界队列当瞬时任务量大时会有OOM的风险
2)CachedThreadPool:大小无界的线程池,适用于很多的短时间的任务执行,适用于负载较轻的服务器.
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
最大线程数是Integer.MAX_VALUE是高度可伸缩的线程,当任务量大时会无限创建线程直到OOM
3)SingleThread:适用于任务需要保证顺序执行
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
输入的线程数就是核心线程数也是最大线程数,会有OOM的风险
4)ScheduledThreadPool:支持定时及周期任务执行,但是线程数最大Integer.MAX_VALUE,也会OOM
ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
ScheduledThreadPoolExecutor会把待调度任务(ScheduledFutureTask)放到DelayQueue中:
ScheduledFutureTask是ScheduledThreadPoolExecutor私有类,3个成员变量
time(long):此任务具体执行时间
sequenceNumber(long ):此任务被添加到ScheduledThreadPoolExecutor中的序号
period( long ):任务执行的间隔周期。
DelayQueue封装了ProorityQueue,time小的排在前面(时间早的先执行),如果time一样sequenceNumber小的先执行.