7中新增的CPU和负载的监控

7中新增的CPU和负载的监控

java 7中新增的CPU和负载的监控

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method; /**
* Test
*/
public class Test { public static void main(String[] args) throws InterruptedException {
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
while (true) {
double load;
try {
Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage");
load = (Double)method.invoke(operatingSystemMXBean);
} catch (Throwable e) {
load = -1;
}
int cpu = operatingSystemMXBean.getAvailableProcessors();
if (load >= cpu) {
System.err.println("WARN!!load:" + load + ","+ "cpu:" + cpu);
}
Thread.currentThread().sleep(1 * 1000);
}
} }
05-08 08:41