如何使用java获取CPU使用率?

nay*_*ang 2 java cpu-usage oshi

我想获取CPU使用率来使用java连续更新我的数据库。在第一个循环中,此代码可读取正确的 CPU 使用情况。之后,它返回小于 0 的错误值。所以,我卡住了。

我用的是jdk 1.8.124。

请让我知道如何连续获取CPU使用率。

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.HardwareAbstractionLayer;
Run Code Online (Sandbox Code Playgroud)

源代码

public static void main(String[] args) {
  OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
      .getOperatingSystemMXBean();

  while (true) {
    System.out.println(bean.getProcessCpuLoad());
    System.out.println(bean.getSystemCpuLoad());
        try {
            Thread.sleep(3000);
        }
        catch (Exception e){
            System.out.println(e.toString());
            break;
        }
  }

}
Run Code Online (Sandbox Code Playgroud)

nay*_*ang 5

这是通过使用 Oshi lib 完成的。

我可以每 20 秒获取一次 cpu 使用情况 lib

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.HardwareAbstractionLayer;
Run Code Online (Sandbox Code Playgroud)

源代码

private SystemInfo si = new SystemInfo();
private HardwareAbstractionLayer hal = si.getHardware();
private CentralProcessor cpu = hal.getProcessor();
long[] prevTicks = new long[TickType.values().length];

public static double getCPU()
{
    double cpuLoad = cpu.getSystemCpuLoadBetweenTicks( prevTicks ) * 100;
    prevTicks = cpu.getSystemCpuLoadTicks();
    System.out.println("cpuLoad : " + cpuLoad);
    return cpuLoad;
}

public static void main(String[] args) throws Exception{
    while(true) {
        // Sleep 20 seconds
        tCPU = (int)getCPU();
    }
}
Run Code Online (Sandbox Code Playgroud)