Java通過Executors提供四種線程池,分別為:
獲取線程池:ExecutorService pool= Executors.newCachedThreadPool()等
1、newCachedThreadPool:線程池Integer.MAX_VALUE無限大,60秒內(nèi)能夠重用已創(chuàng)建的線程,當執(zhí)行第二個任務(wù)時第一個任務(wù)已經(jīng)完成,會復用執(zhí)行第一個任務(wù)的線程(60秒內(nèi)),而不用每次新建線程。
構(gòu)造一個緩沖功能的線程池,配置corePoolSize=0,maximumPoolSize=Integer.MAX_VALUE,keepAliveTime=60s,以及一個無容量的阻塞隊列 SynchronousQueue,因此任務(wù)提交之后,將會創(chuàng)建新的線程執(zhí)行;線程空閑超過60s將會銷毀
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
}
2、newFixedThreadPool:創(chuàng)建一個定長線程池,可控制線程最大并發(fā)數(shù),超出的線程會在隊列中等待。
構(gòu)造一個固定線程數(shù)目的線程池,配置的corePoolSize與maximumPoolSize大小相同,同時使用了一個無界LinkedBlockingQueue存放阻塞任務(wù),因此多余的任務(wù)將存在再阻塞隊列,不會由RejectedExecutionHandler處理 。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
}
3、newSingleThreadExecutor:創(chuàng)建一個單線程化的線程池,它只會用唯一的工作線程來執(zhí)行任務(wù),保證所有任務(wù)按照指定順序(FIFO, LIFO, 優(yōu)先級)執(zhí)行。
構(gòu)造一個只支持一個線程的線程池,配置corePoolSize=maximumPoolSize=1,無界阻塞隊列LinkedBlockingQueue;保證任務(wù)由一個線程串行執(zhí)行
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()));
}
4、newScheduledThreadPool創(chuàng)建一個固定長度的線程池,而且以延遲或定時的方式來執(zhí)行任務(wù)。
構(gòu)造有定時功能的線程池,配置corePoolSize,無界延遲阻塞隊列DelayedWorkQueue;有意思的是:maximumPoolSize=Integer.MAX_VALUE,由于DelayedWorkQueue是無界隊列,所以這個值是沒有意義的
public static ExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPool(corePoolSize,
Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue());
}
注:線程池拒絕策略對無界隊列 不起作用