前言:jdk提供了一套下線程池參數動態化的api,阻塞隊列的長度考慮lilnked擴容機制 import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolChangeDemo { public static void main(String[] args) throws InterruptedException { dynamicThreadPool(); } public static ThreadPoolExecutor buildThreadPool(){ return new ThreadPoolExecutor(2, 50, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(50), new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(); } }); } private static void dynamicThreadPool() throws InterruptedException { ThreadPoolExecutor threadPoolExecutor = buildThreadPool(); for (int i = 0; i < 15; i++) { threadPoolExecutor.submit(()->{ printPoolSize(threadPoolExecutor,"創建線程池!!!!"); try { TimeUnit.SECONDS.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } }); } printPoolSize(threadPoolExecutor,"改變之前"); TimeUnit.SECONDS.sleep(1); threadPoolExecutor.setMaximumPoolSize(100); threadPoolExecutor.setCorePoolSize(50); threadPoolExecutor.prestartAllCoreThreads(); // Resize linkedBlockingQueue = (LinkedBlockingQueue) threadPoolExecutor.getQueue(); printPoolSize(threadPoolExecutor,"改變之後"); } private static void printPoolSize(ThreadPoolExecutor pool,String name){ LinkedBlockingQueue linkedBlockingQueue = (LinkedBlockingQueue) pool.getQueue(); System.out.println(name); System.out.println("最大線程數:"+pool.getMaximumPoolSize()); System.out.println("核心線程數:"+pool.getCorePoolSize()); System.out.println("線程池活躍度:"+(pool.getActiveCount()/pool.getMaximumPoolSize())); System.out.println("隊列大小:"+linkedBlockingQueue.size()); System.out.println("隊列剩餘大小:"+linkedBlockingQueue.remainingCapacity()); } }
java線程池參數動態化方案
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.