參考文章:ThreadPoolExecutor使用詳解
參考文章:ThreadPoolExecutor線程池解析與BlockingQueue的三種實(shí)現(xiàn)
構(gòu)造有定時(shí)功能的線程池,配置corePoolSize,無界延遲阻塞隊(duì)列DelayedWorkQueue;有意思的是:maximumPoolSize=Integer.MAX_VALUE,由于DelayedWorkQueue是 無界隊(duì)列,所以這個(gè)值是沒有意義的
對(duì)于無界隊(duì)列來說,總是可以加入的(資源耗盡,當(dāng)然另當(dāng)別論)。換句說,永遠(yuǎn)也不會(huì)觸發(fā)產(chǎn)生新的線程!corePoolSize大小的線程數(shù)會(huì)一直運(yùn)行,忙完當(dāng)前的,就從隊(duì)列中拿任務(wù)開始運(yùn)行。所以要防止任務(wù)瘋長(zhǎng),比如任務(wù)運(yùn)行的實(shí)行比較長(zhǎng),而添加任務(wù)的速度遠(yuǎn)遠(yuǎn)超過處理任務(wù)的時(shí)間,而且還不斷增加,如果任務(wù)內(nèi)存大一些,不一會(huì)兒就爆了
固定線程數(shù)量的,有定時(shí)功能的線程池
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
}