測試線程池最大線程數。
首先註冊一個線程池
@Bean("threadPool") public ExecutorService buildThreadPoolExecutor(){ //keepAliveTime 的時間單位 TimeUnit unit = TimeUnit.MILLISECONDS; //用來儲存等待執行任務的隊列 LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(2); //線程工廠 ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("log-pool-%d").build(); //拒絕策略。這裏使用 丟棄任務並拋出RejectedExecutionException異常 RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy(); log.info("全局線程池創建成功,線程池核心池的大小:{},線程池的最大線程數:{},當線程數大於核心時,此爲終止前多餘的空閒線程等待新任務的最長時間:{}", 1, 2, 0); //自定義線程池 return new ThreadPoolExecutor(1, 2, 0, unit, workQueue, namedThreadFactory, handler); }
我這裏設置了核心線程池的大小和最大線程數量,注意,如果線程池已經滿了,就會放到等待執行的隊列中,我這裏將 LinkedBlockingQueue 設置爲 2,也就是隊列最大也就2的深度,一旦超過了緩存隊列的深度,就會觸發拒絕策略,這裏的策略是拋出異常,無法執行的時候,拋出 RejectedExecutionException 異常。
所以要做判斷線程是否還有空餘位置,只要加入判斷隊列即可。
// 排隊的線程數量 int size = threadPool.getQueue().size(); // 當前線程池中正在執行任務的線程數量 int activeCount = threadPool.getActiveCount(); // 線程池當前的線程數量 int poolSize = threadPool.getPoolSize(); int corePoolSize = threadPool.getCorePoolSize(); int maximumPoolSize = threadPool.getMaximumPoolSize(); System.out.println("size:" + size + " activeCount:" + activeCount + " poolSize:" + poolSize + " corePoolSize:" + corePoolSize + " maximumPoolSize:" + maximumPoolSize); // 這裏的 6 就是 LinkedBlockingQueue 的大小。上面我設置的是2,後面改成了6測試 if (size >= 6){ return "任務隊列已滿"; }