展开全部
1、确定当前系统安装的jdk是1.6版本以上
2、windows系统中有获取cpu使用率的可执行文636f70793231313335323631343130323136353331333337626230件exe,只要在java中获取该文件的执行路径,通过Java调用即可。
3、获取操作系统可执行文件目录procCmd
4、调用java的Runtime.getRuntime().exec执行cmd应用程序
5、利用java中sleep来计算睡眠前后cpu的忙碌时间与空闲时间,因为sleep不会释放系统资源
6、根据忙碌时间占总时间的比例来计算cpu使用率
示例:private double getCpuRatioForWindows() {
try {
String procCmd = System.getenv("windir")
+ "//system32//wbem//wmic.exe process get Caption,CommandLine,"
+ "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
// 取进程信息
long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
Thread.sleep(CPUTIME);
long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
if (c0 != null && c1 != null) {
long idletime = c1[0] - c0[0];
long busytime = c1[1] - c0[1];
return Double.valueOf(
PERCENT * (busytime) / (busytime + idletime))
.doubleValue();
} else {
return 0.0;
}
} catch (Exception ex) {
ex.printStackTrace();
return 0.0;
}
}