1.創建線程池:
new ThreadPoolExecutor( int corePoolSize, // 核心線程數量(存活)
int maximumPoolSize, // 最大線程數量
long keepAliveTime, // 線程最大的存活時間(當線程數大於核心線程數量多於線程的空閒時間)
TimeUnit unit, // 時間單位
BlockingQueue<Runnable> workQueue, // 工作隊列
ThreadFactory threadFactory, // 用來構造線程池裏的worker線程
RejectedExecutionHandler handler // 超出線程範圍和隊列容量的任務的處理程序
)
handler :
1、AbortPolicy:直接拋出異常
2、CallerRunsPolicy:只用調用所在的線程運行任務
3、DiscardOldestPolicy:丟棄隊列裏最近的一個任務,並執行當前任務。
4、DiscardPolicy:丟棄
2.Executors提供的四種線程池:
2.1 Executors.newSingleThreadExecutor(); 對應參數corePoolSize:1,maximumPoolSize:1
單線程的線程池,多於請求存放在隊列,依次執行
2.2 Executors.newFixedThreadPool(5); 對應參數corePoolSize:5,maximumPoolSize:5
定長線程池,可控制線程最大併發數,超出的線程會在隊列中等待
2.3 Executors.newScheduledThreadPool(5) 對應參數corePoolSize:5,maximumPoolSize:MAX_VALUE
定長線程池,支持定時及週期性任務執行
2.4 Executors.newCachedThreadPool() 對應參數corePoolSize:0,maximumPoolSize:MAX_VALUE
可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閒線程,若無可回收,則新建線程