參考文章:ThreadPoolExecutor使用詳解
參考文章:ThreadPoolExecutor線程池解析與BlockingQueue的三種實現(xiàn)
構(gòu)造有定時功能的線程池,配置corePoolSize,無界延遲阻塞隊列DelayedWorkQueue当纱;有意思的是:maximumPoolSize=Integer.MAX_VALUE屡立,由于DelayedWorkQueue是 無界隊列邮府,所以這個值是沒有意義的
對于無界隊列來說俺猿,總是可以加入的(資源耗盡魏颓,當然另當別論)。換句說鼻听,永遠也不會觸發(fā)產(chǎn)生新的線程财著!corePoolSize大小的線程數(shù)會一直運行,忙完當前的撑碴,就從隊列中拿任務(wù)開始運行撑教。所以要防止任務(wù)瘋長,比如任務(wù)運行的實行比較長醉拓,而添加任務(wù)的速度遠遠超過處理任務(wù)的時間伟姐,而且還不斷增加,如果任務(wù)內(nèi)存大一些廉嚼,不一會兒就爆了
固定線程數(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);
}