一、线程池作用
- 复用已有的资源,解决频繁创建和销毁线程带来的开销
- 控制资源的总数,解决线程创建时数量不可控
优势:
- 可限流,控制线程数量
- 降低频繁创建和销毁线程带来的性能开销
- 对于任务响应速度更快
二、java中提供的线程池
jdk、spring
ThreadPoolExecutor实例
变量 ctl 32bit
高3位代表当前的线程池状态
低29位代表当前的线程数量
command = new App() implement Runable;
addworker(command,true);
1.添加工作线程数(cas添加工作线程数量)
2.创建工作线程
Executors线程池工厂类实际调用重载的new ThreadPoolExecutor()构造方法
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
1. 固定容量的线程池:Executors.newFixedThreadPool
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
2. 定时/周期 定长的线程池:Executors. newScheduledThreadPool
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
3. 创建一个可缓存线程池:Executors.newCachedThreadPool
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
4. 单线程化的线程池:Executors.newSingleThreadExecutor
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
问题:KeepaliveTime,怎么去监控线程进行回收?
三、ThreadPoolExecutor构造参数
01核心线程数、02最大线程数、03活跃时间、
04活跃时间单位、05阻塞队列:线程池超过核心线程数进队列
06线程工厂实例、07拒绝策略Hander:线程池超过最大线程数且队列满了时会调用饱和策略
