Java通過調用Top命令擷取Linux的CPU和記憶體使用量情況__linux

來源:互聯網
上載者:User

在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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.