要查看Java線程池的狀態,我們可以使用ThreadPoolExecutor
類的一些方法。以下是一些常用的方法:
getPoolSize()
:獲取當前線程池中的線程數。getActiveCount()
:獲取正在執行任務的線程數。getCompletedTaskCount()
:獲取已完成的任務數。getTaskCount()
:獲取提交給線程池的總任務數。isShutdown()
:判斷線程池是否已經關閉。isTerminated()
:判斷線程池是否已經終止。另外,你還可以使用java.util.concurrent.ThreadPoolExecutor
類的toString()
方法來打印線程池的一些詳細信息,例如線程池的當前狀態、核心線程數、最大線程數、工作隊列大小等。
以下是一個示例代碼,演示了如何查看線程池的狀態:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolStatusExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
// 提交一些任務給線程池
for (int i = 0; i < 10; i++) {
executorService.execute(() -> {
try {
Thread.sleep(1000);
System.out.println("Task executed by thread: " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
// 輸出線程池的狀態
System.out.println("Pool Size: " + ((ThreadPoolExecutor) executorService).getPoolSize());
System.out.println("Active Count: " + ((ThreadPoolExecutor) executorService).getActiveCount());
System.out.println("Completed Task Count: " + ((ThreadPoolExecutor) executorService).getCompletedTaskCount());
System.out.println("Task Count: " + ((ThreadPoolExecutor) executorService).getTaskCount());
System.out.println("Is Shut Down: " + ((ThreadPoolExecutor) executorService).isShutdown());
System.out.println("Is Terminated: " + ((ThreadPoolExecutor) executorService).isTerminated());
// 關閉線程池
executorService.shutdown();
}
}
以上代碼創建了一個固定線程數為5的線程池,提交了10個任務給線程池。然后通過強制轉換為ThreadPoolExecutor
類型,使用相關方法獲取線程池的狀態信息。最后,調用shutdown()
方法關閉線程池。