Java執行緒池執行狀態監控實現解析
阿新 • • 發佈:2020-11-27
在實際開發過程中,線上程池使用過程中可能會遇到各方面的故障,如執行緒池阻塞,無法提交新任務等。
如果你想監控某一個執行緒池的執行狀態,執行緒池執行類 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); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援碼農教程。