參考:https://blog.csdn.net/l18848956739/article/details/89363321
但在實際開發過程中,在線程池使用過程中可能會遇到各方面的故障,如線程池阻塞,無法提交新任務等。
如果你想監控某一個線程池的執行狀態,線程池執行類 ThreadPoolExecutor
也給出了相關的 API, 能實時獲取線程池的當前活動線程數、正在排隊中的線程數、已經執行完成的線程數、總線程數等。
總線程數 = 排隊線程數 + 活動線程數 + 執行完成的線程數。
線程池使用示例:
private static ExecutorService es = new ThreadPoolExecutor(50, 100, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(100000)); public static void main(String[] args) throws Exception { for (int i = 0; i < 100000; i++) { es.execute(() -> { System.out.print(1); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }); } ThreadPoolExecutor tpe = ((ThreadPoolExecutor) es); while (true) { System.out.println(); int queueSize = tpe.getQueue().size(); System.out.println("當前排隊線程數:" + queueSize); int activeCount = tpe.getActiveCount(); System.out.println("當前活動線程數:" + activeCount); long completedTaskCount = tpe.getCompletedTaskCount(); System.out.println("執行完成線程數:" + completedTaskCount); long taskCount = tpe.getTaskCount(); System.out.println("總線程數:" + taskCount); Thread.sleep(3000); } }