一. 線程池簡介
1. 線程池的概念:javascript
線程池就是首先建立一些線程,它們的集合稱爲線程池。使用線程池能夠很好地提升性能,線程池在系統啓動時即建立大量空閒的線程,程序將一個任務傳給線程池,線程池就會啓動一條線程來執行這個任務,執行結束之後,該線程並不會死亡,而是再次返回線程池中成爲空閒狀態,等待執行下一個任務。java
2. 線程池的工做機制編程
2.1 在線程池的編程模式下,任務是提交給整個線程池,而不是直接提交給某個線程,線程池在拿到任務後,就在內部尋找是否有空閒的線程,若是有,則將任務交給某個空閒的線程。數組
2.1 一個線程同時只能執行一個任務,但能夠同時向一個線程池提交多個任務。緩存
3. 使用線程池的緣由:安全
多線程運行時間,系統不斷的啓動和關閉新線程,成本很是高,會過渡消耗系統資源,以及過渡切換線程的危險,從而可能致使系統資源的崩潰。這時,線程池就是最好的選擇了。多線程
二. 四種常見的線程池詳解
1. 線程池的返回值ExecutorService簡介:併發
ExecutorService是Java提供的用於管理線程池的類。該類的兩個做用:控制線程數量和重用線程異步
2. 具體的4種經常使用的線程池實現以下:(返回值都是ExecutorService)ide
2.1 Executors.newCacheThreadPool():可緩存線程池,先查看池中有沒有之前創建的線程,若是有,就直接使用。若是沒有,就建一個新的線程加入池中,緩存型池子一般用於執行一些生存期很短的異步型任務
示例代碼:
![](http://static.javashuo.com/static/loading.gif)
1 package com.study.test; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 6 public class ThreadPoolExecutorTest { 7 public static void main(String[] args) { 8 //建立一個可緩存線程池 9 ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); 10 for (int i = 0; i < 10; i++) { 11 try { 12 //sleep可明顯看到使用的是線程池裏面之前的線程,沒有建立新的線程 13 Thread.sleep(1000); 14 } catch (InterruptedException e) { 15 e.printStackTrace(); 16 } 17 cachedThreadPool.execute(new Runnable() { 18 public void run() { 19 //打印正在執行的緩存線程信息 20 System.out.println(Thread.currentThread().getName()+"正在被執行"); 21 } 22 }); 23 } 24 } 25 }
輸出結果:
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
線程池爲無限大,當執行當前任務時上一個任務已經完成,會複用執行上一個任務的線程,而不用每次新建線程
2.2 Executors.newFixedThreadPool(int n):建立一個可重用固定個數的線程池,以共享的無界隊列方式來運行這些線程。
示例代碼:
![](http://static.javashuo.com/static/loading.gif)
1 package com.study.test; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 6 public class ThreadPoolExecutorTest { 7 public static void main(String[] args) { 8 //建立一個可重用固定個數的線程池 9 ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); 10 for (int i = 0; i < 10; i++) { 11 fixedThreadPool.execute(new Runnable() { 12 public void run() { 13 try { 14 //打印正在執行的緩存線程信息 15 System.out.println(Thread.currentThread().getName()+"正在被執行"); 16 Thread.sleep(2000); 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 } 21 }); 22 } 23 } 24 }
輸出結果:
pool-1-thread-1正在被執行
pool-1-thread-2正在被執行
pool-1-thread-3正在被執行
pool-1-thread-1正在被執行
pool-1-thread-2正在被執行
pool-1-thread-3正在被執行
pool-1-thread-1正在被執行
pool-1-thread-2正在被執行
pool-1-thread-3正在被執行
pool-1-thread-1正在被執行
由於線程池大小爲3,每一個任務輸出打印結果後sleep 2秒,因此每兩秒打印3個結果。
定長線程池的大小最好根據系統資源進行設置。如Runtime.getRuntime().availableProcessors()
2.3 Executors.newScheduledThreadPool(int n):建立一個定長線程池,支持定時及週期性任務執行
延遲執行示例代碼:
![](http://static.javashuo.com/static/loading.gif)
1 package com.study.test; 2 3 import java.util.concurrent.Executors; 4 import java.util.concurrent.ScheduledExecutorService; 5 import java.util.concurrent.TimeUnit; 6 7 public class ThreadPoolExecutorTest { 8 public static void main(String[] args) { 9 //建立一個定長線程池,支持定時及週期性任務執行——延遲執行 10 ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); 11 //延遲1秒執行 12 scheduledThreadPool.schedule(new Runnable() { 13 public void run() { 14 System.out.println("延遲1秒執行"); 15 } 16 }, 1, TimeUnit.SECONDS); 17 } 18 }
輸出結果:延遲1秒執行
按期執行示例代碼:
![](http://static.javashuo.com/static/loading.gif)
1 package com.study.test; 2 3 import java.util.concurrent.Executors; 4 import java.util.concurrent.ScheduledExecutorService; 5 import java.util.concurrent.TimeUnit; 6 7 public class ThreadPoolExecutorTest { 8 public static void main(String[] args) { 9 //建立一個定長線程池,支持定時及週期性任務執行——按期執行 10 ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); 11 //延遲1秒後每3秒執行一次 12 scheduledThreadPool.scheduleAtFixedRate(new Runnable() { 13 public void run() { 14 System.out.println("延遲1秒後每3秒執行一次"); 15 } 16 }, 1, 3, TimeUnit.SECONDS); 17 } 18 }
輸出結果:
延遲1秒後每3秒執行一次
延遲1秒後每3秒執行一次
.............
2.4 Executors.newSingleThreadExecutor():建立一個單線程化的線程池,它只會用惟一的工做線程來執行任務,保證全部任務按照指定順序(FIFO, LIFO, 優先級)執行。
示例代碼:
![](http://static.javashuo.com/static/loading.gif)
1 package com.study.test; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 6 public class TestThreadPoolExecutor { 7 public static void main(String[] args) { 8 //建立一個單線程化的線程池 9 ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); 10 for (int i = 0; i < 10; i++) { 11 final int index = i; 12 singleThreadExecutor.execute(new Runnable() { 13 public void run() { 14 try { 15 //結果依次輸出,至關於順序執行各個任務 16 System.out.println(Thread.currentThread().getName()+"正在被執行,打印的值是:"+index); 17 Thread.sleep(1000); 18 } catch (InterruptedException e) { 19 e.printStackTrace(); 20 } 21 } 22 }); 23 } 24 } 25 }
輸出結果:
pool-1-thread-1正在被執行,打印的值是:0
pool-1-thread-1正在被執行,打印的值是:1
pool-1-thread-1正在被執行,打印的值是:2
pool-1-thread-1正在被執行,打印的值是:3
pool-1-thread-1正在被執行,打印的值是:4
pool-1-thread-1正在被執行,打印的值是:5
pool-1-thread-1正在被執行,打印的值是:6
pool-1-thread-1正在被執行,打印的值是:7
pool-1-thread-1正在被執行,打印的值是:8
pool-1-thread-1正在被執行,打印的值是:9
三. 緩衝隊列BlockingQueue和自定義線程池ThreadPoolExecutor
1. 緩衝隊列BlockingQueue簡介:
BlockingQueue是雙緩衝隊列。BlockingQueue內部使用兩條隊列,容許兩個線程同時向隊列一個存儲,一個取出操做。在保證併發安全的同時,提升了隊列的存取效率。
2. 經常使用的幾種BlockingQueue:
-
ArrayBlockingQueue(int i):規定大小的BlockingQueue,其構造必須指定大小。其所含的對象是FIFO順序排序的。
-
LinkedBlockingQueue()或者(int i):大小不固定的BlockingQueue,若其構造時指定大小,生成的BlockingQueue有大小限制,不指定大小,其大小有Integer.MAX_VALUE來決定。其所含的對象是FIFO順序排序的。
-
PriorityBlockingQueue()或者(int i):相似於LinkedBlockingQueue,可是其所含對象的排序不是FIFO,而是依據對象的天然順序或者構造函數的Comparator決定。
-
SynchronizedQueue():特殊的BlockingQueue,對其的操做必須是放和取交替完成。
3. 自定義線程池(ThreadPoolExecutor和BlockingQueue連用):
自定義線程池,能夠用ThreadPoolExecutor類建立,它有多個構造方法來建立線程池。
常見的構造函數:ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
示例代碼:
![](http://static.javashuo.com/static/loading.gif)
1 package com.study.test; 2 3 import java.util.concurrent.ArrayBlockingQueue; 4 import java.util.concurrent.BlockingQueue; 5 import java.util.concurrent.ThreadPoolExecutor; 6 import java.util.concurrent.TimeUnit; 7 8 class TempThread implements Runnable { 9 10 @Override 11 public void run() { 12 // 打印正在執行的緩存線程信息 13 System.out.println(Thread.currentThread().getName() + "正在被執行"); 14 try { 15 // sleep一秒保證3個任務在分別在3個線程上執行 16 Thread.sleep(1000); 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 } 21 22 } 23 24 public class TestThreadPoolExecutor { 25 public static void main(String[] args) { 26 // 建立數組型緩衝等待隊列 27 BlockingQueue<Runnable> bq = new ArrayBlockingQueue<Runnable>(10); 28 // ThreadPoolExecutor:建立自定義線程池,池中保存的線程數爲3,容許最大的線程數爲6 29 ThreadPoolExecutor tpe = new ThreadPoolExecutor(3, 6, 50, TimeUnit.MILLISECONDS, bq); 30 31 // 建立3個任務 32 Runnable t1 = new TempThread(); 33 Runnable t2 = new TempThread(); 34 Runnable t3 = new TempThread(); 35 // Runnable t4 = new TempThread(); 36 // Runnable t5 = new TempThread(); 37 // Runnable t6 = new TempThread(); 38 39 // 3個任務在分別在3個線程上執行 40 tpe.execute(t1); 41 tpe.execute(t2); 42 tpe.execute(t3); 43 // tpe.execute(t4); 44 // tpe.execute(t5); 45 // tpe.execute(t6); 46 47 // 關閉自定義線程池 48 tpe.shutdown(); 49 } 50 }
輸出結果:
pool-1-thread-1正在被執行pool-1-thread-2正在被執行pool-1-thread-3正在被執行