線程池的種類(lèi)
之前說(shuō)過(guò)ThreadPoolExecutor的用法浇雹,jdkExecutors
包下還封裝了一些其他類(lèi)型的線程池她紫。
newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
顧名思義硅堆,就是創(chuàng)建線程數(shù)量固定的線程池,線程池的corePoolSize
和maximumPoolSize
大小一樣贿讹,并且keepAliveTime
為0渐逃,傳入的隊(duì)列LinkedBlockingQueue
為無(wú)界隊(duì)列。在說(shuō)ThreadPoolExecutor
的時(shí)候也說(shuō)過(guò)民褂,傳入一個(gè)無(wú)界隊(duì)列茄菊,maximumPoolSize
參數(shù)是不起作用的疯潭。
newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
從代碼中也能看得出來(lái),corePoolSize
和maximumPoolSize
都是1面殖,keepAliveTime
是0L, 傳入的隊(duì)列是無(wú)界隊(duì)列竖哩。線程池中永遠(yuǎn)只要一個(gè)線程在工作。
newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
可緩存線程池脊僚,說(shuō)道緩存一般離不開(kāi)過(guò)期時(shí)間相叁,該線程池也是,corePoolSize
設(shè)置為0吃挑,maximumPoolSize
設(shè)置為int最大值钝荡,不同的是,線程池傳入的隊(duì)列是SynchronousQueue
舶衬,一個(gè)同步隊(duì)列埠通,該隊(duì)列沒(méi)有任何容量,每次插入新數(shù)據(jù)逛犹,必須等待消費(fèi)完成端辱。當(dāng)有新任務(wù)到達(dá)時(shí),線程池沒(méi)有線程則創(chuàng)建線程處理虽画,處理完成后該線程緩存60秒舞蔽,過(guò)期后回收,線程過(guò)期前有新任務(wù)到達(dá)時(shí)码撰,則使用緩存的線程來(lái)處理渗柿。
newScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
這個(gè)線程池使用了ScheduledThreadPoolExecutor
,該線程池繼承自ThreadPoolExecutor
, 執(zhí)行任務(wù)的時(shí)候可以指定延遲多少時(shí)間執(zhí)行脖岛,或者周期性執(zhí)行朵栖。