Java - "JUC線程池" 線程狀態與拒絕策略源碼分析
Java多線程系列--“JUC線程池”04之 線程池原理(三)
本章介紹線程池的生命周期。在"Java多線程系列--“基礎篇”01之 基本概念"中,我們介紹過,線程有5種狀態:新建狀態,就緒狀態,運行狀態,阻塞狀態,死亡狀態。線程池也有5種狀態;然而,線程池不同於線程,線程池的5種狀態是:Running, SHUTDOWN, STOP, TIDYING, TERMINATED。
線程池狀態定義代碼如下:
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0)); private static final int COUNT_BITS = Integer.SIZE - 3; private static final int CAPACITY = (1 << COUNT_BITS) - 1; private static final int RUNNING = -1 << COUNT_BITS; private static final int SHUTDOWN = 0 << COUNT_BITS; private static final int STOP = 1 << COUNT_BITS; private static final int TIDYING = 2 << COUNT_BITS; private static final int TERMINATED = 3 << COUNT_BITS; private static int ctlOf(int rs, int wc) { return rs | wc; }
說明:
ctl是一個AtomicInteger類型的原子對象。ctl記錄了"線程池中的任務數量"和"線程池狀態"2個信息。
ctl共包括32位。其中,高3位表示"線程池狀態",低29位表示"線程池中的任務數量"。
RUNNING -- 對應的高3位值是111。 SHUTDOWN -- 對應的高3位值是000。 STOP -- 對應的高3位值是001。 TIDYING -- 對應的高3位值是010。 TERMINATED -- 對應的高3位值是011。
線程池各個狀態之間的切換如下圖所示:
1. RUNNING
(01) 狀態說明:線程池處在RUNNING狀態時,能夠接收新任務,以及對已添加的任務進行處理。
(02) 狀態切換:線程池的初始化狀態是RUNNING。換句話說,線程池被一旦被創建,就處於RUNNING狀態!
道理很簡單,在ctl的初始化代碼中(如下),就將它初始化為RUNNING狀態,並且"任務數量"初始化為0。
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
2. SHUTDOWN
(01) 狀態說明:線程池處在SHUTDOWN狀態時,不接收新任務,但能處理已添加的任務。
(02) 狀態切換:調用線程池的shutdown()接口時,線程池由RUNNING -> SHUTDOWN。
3. STOP
(01) 狀態說明:線程池處在STOP狀態時,不接收新任務,不處理已添加的任務,並且會中斷正在處理的任務。
(02) 狀態切換:調用線程池的shutdownNow()接口時,線程池由(RUNNING or SHUTDOWN ) -> STOP。
4. TIDYING
(01) 狀態說明:當所有的任務已終止,ctl記錄的"任務數量"為0,線程池會變為TIDYING狀態。當線程池變為TIDYING狀態時,會執行鉤子函數terminated()。terminated()在ThreadPoolExecutor類中是空的,若用戶想在線程池變為TIDYING時,進行相應的處理;可以通過重載terminated()函數來實現。
(02) 狀態切換:當線程池在SHUTDOWN狀態下,阻塞隊列為空並且線程池中執行的任務也為空時,就會由 SHUTDOWN -> TIDYING。
當線程池在STOP狀態下,線程池中執行的任務為空時,就會由STOP -> TIDYING。
5. TERMINATED
(01) 狀態說明:線程池徹底終止,就變成TERMINATED狀態。
(02) 狀態切換:線程池處在TIDYING狀態時,執行完terminated()之後,就會由 TIDYING -> TERMINATED。
拒絕策略介紹
線程池的拒絕策略,是指當任務添加到線程池中被拒絕,而采取的處理措施。
當任務添加到線程池中之所以被拒絕,可能是由於:第一,線程池異常關閉。第二,任務數量超過線程池的最大限制。
線程池共包括4種拒絕策略,它們分別是:AbortPolicy, CallerRunsPolicy, DiscardOldestPolicy和DiscardPolicy。
AbortPolicy -- 當任務添加到線程池中被拒絕時,它將拋出 RejectedExecutionException 異常。 CallerRunsPolicy -- 當任務添加到線程池中被拒絕時,會在線程池當前正在運行的Thread線程池中處理被拒絕的任務。 DiscardOldestPolicy -- 當任務添加到線程池中被拒絕時,線程池會放棄等待隊列中最舊的未處理任務,然後將被拒絕的任務添加到等待隊列中。 DiscardPolicy -- 當任務添加到線程池中被拒絕時,線程池將丟棄被拒絕的任務。
線程池默認的處理策略是AbortPolicy!
拒絕策略對比和示例
下面通過示例,分別演示線程池的4種拒絕策略。
1. DiscardPolicy 示例
2. DiscardOldestPolicy 示例
3. AbortPolicy 示例
4. CallerRunsPolicy 示例
1. DiscardPolicy 示例
1 import java.lang.reflect.Field; 2 import java.util.concurrent.ArrayBlockingQueue; 3 import java.util.concurrent.ThreadPoolExecutor; 4 import java.util.concurrent.TimeUnit; 5 import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy; 6 7 public class DiscardPolicyDemo { 8 9 private static final int THREADS_SIZE = 1; 10 private static final int CAPACITY = 1; 11 12 public static void main(String[] args) throws Exception { 13 14 // 創建線程池。線程池的"最大池大小"和"核心池大小"都為1(THREADS_SIZE),"線程池"的阻塞隊列容量為1(CAPACITY)。 15 ThreadPoolExecutor pool = new ThreadPoolExecutor(THREADS_SIZE, THREADS_SIZE, 0, TimeUnit.SECONDS, 16 new ArrayBlockingQueue<Runnable>(CAPACITY)); 17 // 設置線程池的拒絕策略為"丟棄" 18 pool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); 19 20 // 新建10個任務,並將它們添加到線程池中。 21 for (int i = 0; i < 10; i++) { 22 Runnable myrun = new MyRunnable("task-"+i); 23 pool.execute(myrun); 24 } 25 // 關閉線程池 26 pool.shutdown(); 27 } 28 } 29 30 class MyRunnable implements Runnable { 31 private String name; 32 public MyRunnable(String name) { 33 this.name = name; 34 } 35 @Override 36 public void run() { 37 try { 38 System.out.println(this.name + " is running."); 39 Thread.sleep(100); 40 } catch (Exception e) { 41 e.printStackTrace(); 42 } 43 } 44 }
運行結果:
task-0 is running. task-1 is running.
結果說明:線程池pool的"最大池大小"和"核心池大小"都為1(THREADS_SIZE),這意味著"線程池能同時運行的任務數量最大只能是1"。
線程池pool的阻塞隊列是ArrayBlockingQueue,ArrayBlockingQueue是一個有界的阻塞隊列,ArrayBlockingQueue的容量為1。這也意味著線程池的阻塞隊列只能有一個線程池阻塞等待。
根據""中分析的execute()代碼可知:線程池中共運行了2個任務。第1個任務直接放到Worker中,通過線程去執行;第2個任務放到阻塞隊列中等待。其他的任務都被丟棄了!
2. DiscardOldestPolicy 示例
1 import java.lang.reflect.Field; 2 import java.util.concurrent.ArrayBlockingQueue; 3 import java.util.concurrent.ThreadPoolExecutor; 4 import java.util.concurrent.TimeUnit; 5 import java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy; 6 7 public class DiscardOldestPolicyDemo { 8 9 private static final int THREADS_SIZE = 1; 10 private static final int CAPACITY = 1; 11 12 public static void main(String[] args) throws Exception { 13 14 // 創建線程池。線程池的"最大池大小"和"核心池大小"都為1(THREADS_SIZE),"線程池"的阻塞隊列容量為1(CAPACITY)。 15 ThreadPoolExecutor pool = new ThreadPoolExecutor(THREADS_SIZE, THREADS_SIZE, 0, TimeUnit.SECONDS, 16 new ArrayBlockingQueue<Runnable>(CAPACITY)); 17 // 設置線程池的拒絕策略為"DiscardOldestPolicy" 18 pool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy()); 19 20 // 新建10個任務,並將它們添加到線程池中。 21 for (int i = 0; i < 10; i++) { 22 Runnable myrun = new MyRunnable("task-"+i); 23 pool.execute(myrun); 24 } 25 // 關閉線程池 26 pool.shutdown(); 27 } 28 } 29 30 class MyRunnable implements Runnable { 31 private String name; 32 public MyRunnable(String name) { 33 this.name = name; 34 } 35 @Override 36 public void run() { 37 try { 38 System.out.println(this.name + " is running."); 39 Thread.sleep(200); 40 } catch (Exception e) { 41 e.printStackTrace(); 42 } 43 } 44 }
運行結果:
task-0 is running. task-9 is running.
結果說明:將"線程池的拒絕策略"由DiscardPolicy修改為DiscardOldestPolicy之後,當有任務添加到線程池被拒絕時,線程池會丟棄阻塞隊列中末尾的任務,然後將被拒絕的任務添加到末尾。
3. AbortPolicy 示例
1 import java.lang.reflect.Field; 2 import java.util.concurrent.ArrayBlockingQueue; 3 import java.util.concurrent.ThreadPoolExecutor; 4 import java.util.concurrent.TimeUnit; 5 import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; 6 import java.util.concurrent.RejectedExecutionException; 7 8 public class AbortPolicyDemo { 9 10 private static final int THREADS_SIZE = 1; 11 private static final int CAPACITY = 1; 12 13 public static void main(String[] args) throws Exception { 14 15 // 創建線程池。線程池的"最大池大小"和"核心池大小"都為1(THREADS_SIZE),"線程池"的阻塞隊列容量為1(CAPACITY)。 16 ThreadPoolExecutor pool = new ThreadPoolExecutor(THREADS_SIZE, THREADS_SIZE, 0, TimeUnit.SECONDS, 17 new ArrayBlockingQueue<Runnable>(CAPACITY)); 18 // 設置線程池的拒絕策略為"拋出異常" 19 pool.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); 20 21 try { 22 23 // 新建10個任務,並將它們添加到線程池中。 24 for (int i = 0; i < 10; i++) { 25 Runnable myrun = new MyRunnable("task-"+i); 26 pool.execute(myrun); 27 } 28 } catch (RejectedExecutionException e) { 29 e.printStackTrace(); 30 // 關閉線程池 31 pool.shutdown(); 32 } 33 } 34 } 35 36 class MyRunnable implements Runnable { 37 private String name; 38 public MyRunnable(String name) { 39 this.name = name; 40 } 41 @Override 42 public void run() { 43 try { 44 System.out.println(this.name + " is running."); 45 Thread.sleep(200); 46 } catch (Exception e) { 47 e.printStackTrace(); 48 } 49 } 50 }
(某一次)運行結果:
java.util.concurrent.RejectedExecutionException at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1774) at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:768) at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:656) at AbortPolicyDemo.main(AbortPolicyDemo.java:27) task-0 is running. task-1 is running.
結果說明:將"線程池的拒絕策略"由DiscardPolicy修改為AbortPolicy之後,當有任務添加到線程池被拒絕時,會拋出RejectedExecutionException。
4. CallerRunsPolicy 示例
1 import java.lang.reflect.Field; 2 import java.util.concurrent.ArrayBlockingQueue; 3 import java.util.concurrent.ThreadPoolExecutor; 4 import java.util.concurrent.TimeUnit; 5 import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy; 6 7 public class CallerRunsPolicyDemo { 8 9 private static final int THREADS_SIZE = 1; 10 private static final int CAPACITY = 1; 11 12 public static void main(String[] args) throws Exception { 13 14 // 創建線程池。線程池的"最大池大小"和"核心池大小"都為1(THREADS_SIZE),"線程池"的阻塞隊列容量為1(CAPACITY)。 15 ThreadPoolExecutor pool = new ThreadPoolExecutor(THREADS_SIZE, THREADS_SIZE, 0, TimeUnit.SECONDS, 16 new ArrayBlockingQueue<Runnable>(CAPACITY)); 17 // 設置線程池的拒絕策略為"CallerRunsPolicy" 18 pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); 19 20 // 新建10個任務,並將它們添加到線程池中。 21 for (int i = 0; i < 10; i++) { 22 Runnable myrun = new MyRunnable("task-"+i); 23 pool.execute(myrun); 24 } 25 26 // 關閉線程池 27 pool.shutdown(); 28 } 29 } 30 31 class MyRunnable implements Runnable { 32 private String name; 33 public MyRunnable(String name) { 34 this.name = name; 35 } 36 @Override 37 public void run() { 38 try { 39 System.out.println(this.name + " is running."); 40 Thread.sleep(100); 41 } catch (Exception e) { 42 e.printStackTrace(); 43 } 44 } 45 }
(某一次)運行結果:
task-2 is running. task-3 is running. task-4 is running. task-5 is running. task-6 is running. task-7 is running. task-8 is running. task-9 is running. task-0 is running. task-1 is running.
結果說明:將"線程池的拒絕策略"由DiscardPolicy修改為CallerRunsPolicy之後,當有任務添加到線程池被拒絕時,線程池會將被拒絕的任務添加到"線程池正在運行的線程"中取運行。
Java - "JUC線程池" 線程狀態與拒絕策略源碼分析