一、重要參數
corePollSize:核心線程數。在創建了線程池后,線程中沒有任何線程,等到有任務到來時才創建線程去執行任務。
maximumPoolSize:最大線程數。表明線程中最多能夠創建的線程數量。
keepAliveTime:空閑的線程保留的時間。
TimeUnit:空閑線程的保留時間單位。
BlockingQueue:阻塞隊列,存儲等待執行的任務。參數有ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue可選。
ThreadFactory:線程工廠,用來創建線程
RejectedExecutionHandler:隊列已滿,而且任務量大於最大線程的異常處理策略。
ThreadPoolExecutor.AbortPolicy:丟棄任務並拋出RejectedExecutionException異常。
ThreadPoolExecutor.DiscardPolicy:也是丟棄任務,但是不拋出異常。
ThreadPoolExecutor.DiscardOldestPolicy:丟棄隊列最前面的任務,然后重新嘗試執行任務(重復此過程)
ThreadPoolExecutor.CallerRunsPolicy:由調用線程處理該任務
二、四類構造函數
1、 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
2、ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)
3、 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)
4、 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
三、實現線程池的四種策略
1、newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.
MAX_VALUE,
60L, TimeUnit.
SECONDS,
new SynchronousQueue<Runnable>());
}
2、newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.
MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
3、newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
( new ThreadPoolExecutor(1, 1,
0L, TimeUnit.
MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
4、newScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool (int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor( int corePoolSize) {
super(corePoolSize, Integer.
MAX_VALUE, 0, TimeUnit.
NANOSECONDS,
new DelayedWorkQueue());
}