new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,new ThreadPoolExecutor.AbortPolicy())
1.ThreadPoolExecutor.AbortPolicy
線程池的默認拒絕策略為AbortPolicy,即丟棄任務並拋出RejectedExecutionException異常(即后面提交的請求不會放入隊列也不會直接消費並拋出異常);
2.ThreadPoolExecutor.DiscardPolicy
丟棄任務,但是不拋出異常。如果線程隊列已滿,則后續提交的任務都會被丟棄,且是靜默丟棄(也不會拋出任何異常,任務直接就丟棄了)。
3.ThreadPoolExecutor.DiscardOldestPolicy
丟棄隊列最前面的任務,然后重新提交被拒絕的任務(丟棄掉了隊列最前的任務,並不拋出異常,直接丟棄了)。
4.ThreadPoolExecutor.CallerRunsPolicy
由調用線程處理該任務(不會丟棄任務,最后所有的任務都執行了,並不會拋出異常)
使用最好使用默認的拒絕策略。
測試代碼:
public class MainTest { public static void main(String[] args) { //核心線程數 int corePoolSize = 3; //最大線程數 int maximumPoolSize = 6; //超過 corePoolSize 線程數量的線程最大空閑時間 long keepAliveTime = 2; //以秒為時間單位 TimeUnit unit = TimeUnit.SECONDS; //創建工作隊列,用於存放提交的等待執行任務 BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(2); ThreadPoolExecutor threadPoolExecutor = null; try { //Executors. //創建線程池 threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, new ThreadPoolExecutor.CallerRunsPolicy()); //循環提交任務 for (int i = 0; i < 12; i++) { //提交任務的索引 final int index = (i + 1); threadPoolExecutor.submit(() -> { //線程打印輸出 System.out.println("大家好,我是線程:" + index); try { //模擬線程執行時間,10s Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } }); //每個任務提交后休眠500ms再提交下一個任務,用於保證提交順序 Thread.sleep(500); } } catch (InterruptedException e) { e.printStackTrace(); } finally { threadPoolExecutor.shutdown(); } } }