Java多線程導(dǎo)致CPU占用100%解決及線程池正確關(guān)閉方式
簡介
情景:1000萬表數(shù)據(jù)導(dǎo)入內(nèi)存數(shù)據(jù)庫,按分頁大小10000查詢,多線程,15條線程跑。
使用了ExecutorService executor = Executors.newFixedThreadPool(15)
本地跑了一段時間后,發(fā)現(xiàn)電腦CPU逐漸升高,最后CPU占用100%卡死,內(nèi)存使用也高達80%。
排查問題
Debug 發(fā)現(xiàn)雖然創(chuàng)建了定長15的線程池,但是因為數(shù)據(jù)量大,在For中循環(huán)分頁查詢的List會持續(xù)加入LinkedBlockingQueue
隊列中每一個等待的任務(wù),又加載了1萬的數(shù)據(jù)。所以不管是線程數(shù)的CPU搶占,還是內(nèi)存的消耗都是極高。
所以是不是能夠控制等待隊列LinkedBlockingQueue的上限就可以了。

解決辦法
使用AtomicLong 統(tǒng)計線程是否完成,再執(zhí)行executor.submit()提交新的任務(wù)導(dǎo)隊列中。
偽代碼如下:
private AtomicLong threadNum = new AtomicLong(0);
public void init() throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(15);
Integer total = accountMapper.selectCount(new QueryWrapper<>());
Integer pageSize = 10000; // 頁大小
Integer pageCount = (total + pageSize -1) / pageSize; // 總頁數(shù)
for (Integer start = 1; start <= pageCount; start++) {
List<Account> list = accountMapper.selectPage(new Page<>(start, pageSize), query).getRecords();
//等待線程任務(wù)完成,設(shè)置30,可令運行線程數(shù)為15,等待隊列線程數(shù)為15
while (threadNum.get() >= 30){
Thread.sleep(5000);
}
//開啟1個線程+1
threadNum.incrementAndGet();
executor.submit(() -> {
try {
// 處理業(yè)務(wù)
dealMessage(list);
// 任務(wù)完成 -1
threadNum.decrementAndGet();
} catch (Exception e) {
e.printStackTrace();
}
});
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.DAYS);
}
效果就是CPU保持在15~45%之間,內(nèi)存占用也只有45%。
目前只想到這樣的方式,控制等待隊列LinkedBlockingQueue的上限,還有更好的方式請告知,感謝!
2021-02-03-分割線
最近又用到了多線程開發(fā),發(fā)現(xiàn)了還是有很多方式控制的。簡單的使用java的Semaphore令牌限流控制也能實現(xiàn)。
多線程:
- 線程池必須關(guān)閉,main主線程才能結(jié)束(接口才會返回)finally { executorService.shutdown(); }
- 主線程等待保證多線程所有子線程任務(wù)執(zhí)行完畢,再結(jié)束。 -> executorService.awaitTermination(1, TimeUnit.DAYS);
- semaphore 令牌限流控制fixedThread線程池,本例子就是最多同時擁有2個線程進行工作
- fixedThread.execute() fixedThread.submit() 的差別除了后者可以返回結(jié)果外,后者還會catch掉異常信息,無法拋到主線程中。
public static void main(String[] args) {
final List<String> tableNames = new ArrayList<>();
tableNames.add("a");
tableNames.add("b");
tableNames.add("c");
tableNames.add("d");
tableNames.add("e");
tableNames.add("f");
final Semaphore semaphore = new Semaphore(2);
final ExecutorService fixedThread = Executors.newCachedThreadPool();
for (final String tableName : tableNames) {
//阻塞,獲取令牌
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
//do
fixedThread.execute(() -> { //can throw ex log
final ExecutorService executorService = Executors.newCachedThreadPool();
try {
executorService.submit(() -> { //can't throw ex log
//int i = 1/0;
System.out.println("tableName2:" + tableName);
});
//int i = 1/0;
System.out.println("tableName:" + tableName);
} catch (Exception e) {
e.printStackTrace();
} finally {
executorService.shutdown();
try {
executorService.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
semaphore.release();
System.out.println("semaphore.release");
}
});
}
// 記得關(guān)閉線程池
fixedThread.shutdown();
try {
fixedThread.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主線程...");
}
打印結(jié)果
tableName:b
tableName2:b
tableName:a
tableName2:a
semaphore.release
semaphore.release
tableName:d
tableName2:d
tableName:c
semaphore.release
tableName:e
tableName2:c
semaphore.release
tableName:f
tableName2:e
semaphore.release
tableName2:f
semaphore.release
主線程...
到此這篇關(guān)于Java多線程導(dǎo)致CPU占用100%解決及線程池正確關(guān)閉方式的文章就介紹到這了,更多相關(guān)Java多線程CPU占用100%內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring-boot整合ehcache實現(xiàn)緩存機制的方法
spring-boot是一個快速的集成框架,其設(shè)計目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程。這篇文章主要介紹了spring-boot整合ehcache實現(xiàn)緩存機制,需要的朋友可以參考下2018-01-01
java多態(tài)性中的Overload和Override區(qū)別詳解
這篇文章主要介紹了java多態(tài)性中的Overload和Override區(qū)別詳解,重寫(Overriding)是父類與子類之間多態(tài)性的一種表現(xiàn),而重載(Overloading)是一個類中多態(tài)性的一種表現(xiàn),需要的朋友可以參考下2023-07-07
Spring Boot集成Seata實現(xiàn)基于AT模式的分布式事務(wù)的解決方案
Seata 是一款開源的分布式事務(wù)解決方案,致力于提供高性能和簡單易用的分布式事務(wù)服務(wù),這篇文章主要介紹了Spring Boot集成Seata實現(xiàn)基于AT模式的分布式事務(wù),需要的朋友可以參考下2024-08-08
RestTemplate使用Proxy代理作為跳板發(fā)送請求
這篇文章主要為大家介紹了RestTemplate使用代理proxy作為跳板發(fā)送請求的方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-03-03
SpringBoot結(jié)合SpringSecurity實現(xiàn)圖形驗證碼功能
這篇文章主要介紹了SpringBoot + SpringSecurity 實現(xiàn)圖形驗證碼功能,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05

