首先确认你的linux系统支持命令“mpstat -P ALL”,不支持的安装一下就可以了。
我用的是ubuntu,执行命令的结果如下:
我们还说一下我的思路,“mpstat -P ALL”命令可以linux下查看cpu的使用情况,那么我们可以用java代码执行linux的命令,获取返回的结果,对结果进行分析处理就可以了。
下面来看一下代码:
package com.example.demo.utils; import java.io.*; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; /** * 获取linux下每个cpu的使用情况 * */ public class TopUtils { /** * 根据命令返回字符串 * @return */ public static String writeTopMsg() { BufferedReader br = null; String result = ""; try { String cmd = "mpstat -P ALL"; Process ps = Runtime.getRuntime().exec(cmd); br = new BufferedReader(new InputStreamReader(ps.getInputStream())); StringBuffer sb = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } } catch (Exception e1) { e1.printStackTrace(); } } return result; } /** * 计算每个cpu的使用率 * @return */ public static Map<String, String> getCpuUsageRate() { Map<String, String> cpuUsageMap = new HashMap<>(); String cpuStr = writeTopMsg(); String[] cpuArr = cpuStr.split("\n"); if (cpuArr.length > 4) { for (int i = 4; i < cpuArr.length; i++) { //System.out.println(i + ":" + cpuArr[i]); String[] cpuItemArr = cpuArr[i].split("\\s+"); //获取每个cpu名称 Integer num = Integer.parseInt(cpuItemArr[1])+ 1; String cupName="cpu" + num; //计算使用率:100-剩余空间=所有使用 float cpuUsageRate = 100 - Float.parseFloat(cpuItemArr[11]); DecimalFormat decimalFormat = new DecimalFormat("0.00"); cpuUsageMap.put(cupName, decimalFormat.format(cpuUsageRate)); } }//if return cpuUsageMap; } public static void main(String[] args) { Map<String, String> map = getCpuUsageRate(); for (Map.Entry<String, String> cpu : map.entrySet()) { System.out.println(cpu.getKey() + ":" + cpu.getValue()); } } }
执行结果:
cpu2:18.79
cpu3:18.65
cpu1:18.60
cpu4:17.07