原文地址:http://www.voidcn.com/article/p-yehrvmep-uo.html
思路如下:Linux系统中可以用top命令查看进程使用CPU和内存情况,通过Runtime类的exec()方法执行命令"top”,获取"top"的输出,从而得到CPU和内存的使用情况。
使用top命令获取系统信息:
top -b -n -1 | sed -n '3p'(使用sed命令将top输出内容中的第三行打印出来)
%Cpu(s): 6.5 us, 2.2 sy, 0.7 ni, 87.0 id, 3.5 wa, 0.0 hi, 0.1 si, 0.0 st
top -b -n 1 | sed -n '3p' | awk '{print $8}'(将第三行第八列打印出来)
87.0
获取单个进程CPU,内存的占用率
cmd脚本命令:top -b -n 1 -p $pid | sed -n '$p'
上面的$pid,就是进程的PID
Java Runtime类
每个 Java 应用程序都有一个 Runtime
类实例,使应用程序能够与其运行的环境相连接。可以通过 getRuntime
方法获取当前运行时。
应用程序不能创建自己的 Runtime 类实例。
示例程序(针对suse平台,如果是其他Linux,可能需要稍微修改程序)
import java.io.BufferedReader; import java.io.InputStreamReader; public class MySystem { public static float getCpuUsage() { float cpuUsage = 0; float idleUsage = 0; Runtime rt = Runtime.getRuntime(); String[] cmd = { "/bin/sh", "-c", "top -b -n 1 | sed -n '3p' | awk '{print $5}'" };<span style="color:#ff0000;"><strong>//如果使用的命令带有空格、重定向等,必须使用命令串(字符串数组)</strong></span> BufferedReader in = null; Str