一、線程池作用
- 複用已有的資源,解決頻繁建立和銷毀線程帶來的開銷
- 控制資源的總數,解決線程建立時數量不可控
優勢:
- 可限流,控制線程數量
- 降低頻繁建立和銷毀線程帶來的性能開銷
- 對于任務響應速度更快
二、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:線程池超過最大線程數且隊列滿了時會調用飽和政策
