java 7中新增的CPU和負載的監控

FrankYou發表於2018-08-27

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);
        }
    }

}

 

相關文章