温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java多线程导致CPU占用100%怎么办

发布时间:2021-05-27 11:09:48 来源:亿速云 阅读:853 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关Java多线程导致CPU占用100%怎么办的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

简介

情景:1000万表数据导入内存数据库,按分页大小10000查询,多线程,15条线程跑。
使用了ExecutorService executor = Executors.newFixedThreadPool(15)
本地跑了一段时间后,发现电脑CPU逐渐升高,最后CPU占用100%卡死,内存使用也高达80%。

排查问题

Debug 发现虽然创建了定长15的线程池,但是因为数据量大,在For中循环分页查询的List会持续加入LinkedBlockingQueue()
队列中每一个等待的任务,又加载了1万的数据。所以不管是线程数的CPU抢占,还是内存的消耗都是极高。
所以是不是能够控制等待队列LinkedBlockingQueue的上限就可以了。

Java多线程导致CPU占用100%怎么办

解决办法

使用AtomicLong 统计线程是否完成,再执行executor.submit()提交新的任务导队列中。
伪代码如下:

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; // 总页数

	for (Integer start = 1; start <= pageCount; start++) {

		List<Account> list = accountMapper.selectPage(new Page<>(start, pageSize), query).getRecords();

		//等待线程任务完成,设置30,可令运行线程数为15,等待队列线程数为15
		while (threadNum.get() >= 30){
			Thread.sleep(5000);
		}

		//开启1个线程+1
		threadNum.incrementAndGet();
	
		executor.submit(() -> {

			try {
				// 处理业务
				dealMessage(list);
				// 任务完成 -1
				threadNum.decrementAndGet();
			} catch (Exception e) {
				e.printStackTrace();
			}

		});

	}
        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.DAYS);

}

效果就是CPU保持在15~45%之间,内存占用也只有45%。

目前只想到这样的方式,控制等待队列LinkedBlockingQueue的上限,还有更好的方式请告知,感谢!

2021-02-03-分割线
最近又用到了多线程开发,发现了还是有很多方式控制的。简单的使用java的Semaphore令牌限流控制也能实现。

多线程:

  • 线程池必须关闭,main主线程才能结束(接口才会返回)finally { executorService.shutdown(); }

  • 主线程等待保证多线程所有子线程任务执行完毕,再结束。 -> executorService.awaitTermination(1, TimeUnit.DAYS);

  • semaphore 令牌限流控制fixedThread线程池,本例子就是最多同时拥有2个线程进行工作

  • fixedThread.execute() fixedThread.submit() 的差别除了后者可以返回结果外,后者还会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");
            }
        });
    }
    // 记得关闭线程池
    fixedThread.shutdown();
    try {
        fixedThread.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("主线程...");
}

打印结果

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
主线程...

Java的特点有哪些

Java的特点有哪些 1.Java语言作为静态面向对象编程语言的代表,实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程。 2.Java具有简单性、面向对象、分布式、安全性、平台独立与可移植性、动态性等特点。 3.使用Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等。

感谢各位的阅读!关于“Java多线程导致CPU占用100%怎么办”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI