線程池優(yōu)點(diǎn)
- 限流
控制線程總數(shù),根據(jù)硬件人為控制使性能達(dá)到最優(yōu) - 復(fù)用
減少線程的頻繁創(chuàng)建和銷毀復(fù)用線程 - 效率
因為線程可復(fù)用任務(wù)相應(yīng)更快
java中的線程池
Executors.newFixedThreadPool(nThreads);//固定線程數(shù)線程池
Executors.newCachedThreadPool();//有伸縮性線程池,線程60shou后回收
Executors.newSingleThreadExecutor();//只有一個核心線程的線程池
Executors.newSingleThreadScheduledExecutor();//定時任務(wù)線程池
Executors.newWorkStealingPool();//fork/join線程池
- Executors核心構(gòu)造方法
public ThreadPoolExecutor(int corePoolSize,//核心線程數(shù)
int maximumPoolSize,//最大線程數(shù)
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.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
- newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, //核心線程數(shù)=傳入線程數(shù)
nThreads,//最大線程數(shù)=傳入線程數(shù)
0L,//超時間=0
TimeUnit.MILLISECONDS,//超時時間單位=秒
new LinkedBlockingQueue<Runnable>()//雙向鏈表阻塞隊列
);
}
- newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(
0, //核心線程數(shù)=0
Integer.MAX_VALUE,//最大線程數(shù)=Integer最大值(可當(dāng)做無限大)
60L, //超時時間=60
TimeUnit.SECONDS,//超時時間單位=秒
new SynchronousQueue<Runnable>()//不存儲元素的阻塞隊列
);
}
- newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 核心線程數(shù)=1
1,//最大線程數(shù)=1
0L,//超時時間0
TimeUnit.MILLISECONDS,//超時時間單位:毫秒
new LinkedBlockingQueue<Runnable>()//雙向鏈表阻塞隊列
));
}
執(zhí)行流程圖
image.png
問題
- 1.不建議使用Executors創(chuàng)建線程池?為什么?
Executors創(chuàng)建的線程池內(nèi)置的參數(shù),使開發(fā)人員在不用了解線程池各個參數(shù)的含義的情況下進(jìn)行使用.
在實際生產(chǎn)環(huán)境上運(yùn)行是十分危險的 - 2.線程池大小的設(shè)置?
CPU 核數(shù):
IO密集型:每個線程執(zhí)行時間長,cpu利用率低;可以多設(shè)置一些;CPU核數(shù)2或者 (線程等待時間+線程CUP時間)/線程CPU時間cup核數(shù)
CUP密集型:cpu核數(shù)+1
-3.線程池預(yù)熱:
ThreadPollExecutor.prestartAllCoreThreads()
- 4
execute()與 submit()
的區(qū)別
submit(Callable<T>)
執(zhí)行待返回值的任務(wù),根據(jù)返回值可知任務(wù)的執(zhí)行結(jié)果
submit()
不會拋出異常,異常根據(jù)Callable返回