Java線程池運行狀態(tài)監(jiān)控實現(xiàn)解析
在實際開發(fā)過程中,在線程池使用過程中可能會遇到各方面的故障,如線程池阻塞,無法提交新任務(wù)等。
如果你想監(jiān)控某一個線程池的執(zhí)行狀態(tài),線程池執(zhí)行類 ThreadPoolExecutor 也給出了相關(guān)的 API, 能實時獲取線程池的當(dāng)前活動線程數(shù)、正在排隊中的線程數(shù)、已經(jīng)執(zhí)行完成的線程數(shù)、總線程數(shù)等。
總線程數(shù) = 排隊線程數(shù) + 活動線程數(shù) + 執(zhí)行完成的線程數(shù)。
線程池使用示例:
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("當(dāng)前排隊線程數(shù):" + queueSize);
int activeCount = tpe.getActiveCount();
System.out.println("當(dāng)前活動線程數(shù):" + activeCount);
long completedTaskCount = tpe.getCompletedTaskCount();
System.out.println("執(zhí)行完成線程數(shù):" + completedTaskCount);
long taskCount = tpe.getTaskCount();
System.out.println("總線程數(shù):" + taskCount);
Thread.sleep(3000);
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot使用AOP實現(xiàn)統(tǒng)一角色權(quán)限校驗
這篇文章主要介紹了SpringBoot如何使用AOP實現(xiàn) 統(tǒng)一角色權(quán)限校驗,文中有詳細(xì)的代碼示例講解和操作流程,具有一定的參考價值,需要的朋友可以參考下2023-07-07
詳解SpringMVC和MyBatis框架開發(fā)環(huán)境搭建和簡單實用
這篇文章主要介紹了詳解SpringMVC和MyBatis框架開發(fā)環(huán)境搭建和簡單實用,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
java?Stream流常見操作方法(反射,類加載器,類加載,反射)
這篇文章主要介紹了java?Stream流常見操作方法(反射,類加載器,類加載,反射),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,展開詳細(xì)的內(nèi)容介紹,具有一定參考價值,感興趣的小伙伴可以參考一下2022-06-06
Springboot 1.5.7整合Kafka-client代碼示例
這篇文章主要介紹了Springboot 1.5.7整合Kafka-client代碼示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10

