1. 前言
阿里巴巴java手冊中說明:
* 線程資源必須通過線程池提供,不允許在應用中自行顯示創建線程。
說明:使用線程池的好處是減少在創建和銷燬線程上所花的時間以及系統資源的開銷解決資源 不足的問題。 不過不使用線程,有可能造成系統創建大量同類線程而導致消耗完內存或者“過度切換”的問題。
簡單來說使用線程池有以下幾個目的:
- 線程是稀缺資源,不能頻繁的創建。
- 解耦作用;線程的創建與執行完全分開,方便維護。
- 應當將其放入一個池子中,可以給其他任務進行復用。
2.線程池原理
2.1線程池的實現
常見的創建線程池方式方法:
- Executors.newCachedThreadPool():無限線程池。
- Executors.newFixedThreadPool(int nThreads):創建固定大小的線程池。
- Executors.newSingleThreadExecutor():創建單個線程的線程池。
看這三種方式創建的源碼:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
可以發現還是利用ThreadPoolExecutor 類實現的。
創建線程的api:
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)
這幾個核心參數的作用:
- corePoolSize 爲線程池的基本大小。
- maximumPoolSize 爲線程池最大線程大小。
- keepAliveTime 和 unit 則是線程空閒後的存活時間。
- workQueue 用於存放任務的阻塞隊列。
- handler 當隊列和最大線程池都滿了之後的飽和策略。