首先確認你的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