在Java編程過程中希望知道CPU的使用率,以便決定是否載入任務。首先用google搜了一下,Windows環境可以用JNI通過API函數 getProcessCPUTime()來得到,並有人給出了原始碼。Linux好像還沒有誰給出原始碼,於是決定自己寫一個,經過實踐,終於成功,現將 代碼貼出,與大家共用。
思路如下:Linux系統中可以用top命令查看進程使用CPU和記憶體情況,通過Runtime類的exec()方法系統命令"top”,擷取"top"的輸出,從而得到CPU和記憶體的使用方式。對本程式稍加改動,還可以得到記憶體的使用方式。
package com.hmw.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* @author wanlh
* @version 1.0
*/
public class CpuUsage {
public double getCpuUsage() throws Exception {
double cpuUsed = 0;
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("top -b -n 1");// 調用系統的“top"命令
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String str = null;
String[] strArray = null;
while ((str = in.readLine()) != null) {
int m = 0;
if (str.indexOf(" R ") != -1 && str.indexOf("top") == -1) {// 只分析正在啟動並執行進程,top進程本身除外
strArray = str.split(" ");
for (String tmp : strArray) {
if (tmp.trim().length() == 0)
continue;
if (++m == 9) {// 第9列為CPU的使用百分比(RedHat 9)
cpuUsed += Double.parseDouble(tmp);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
in.close();
}
return cpuUsed;
}
public static void main(String[] args) throws Exception {
CpuUsage cpu = new CpuUsage();
System.out.println("cpu used:" + cpu.getCpuUsage() + "%");
}
}
來源: http://www.itpub.net/archiver/tid-859283.html