获取有效的 getSystemCpuLoad()

Get valid getSystemCpuLoad()

我用的是jdk7。我正在尝试通过此语句

获取总 CPU 使用率
System.out.println("getCpuUsage()" + " = " + operatingSystemMXBean.getSystemCpuLoad());

我得到的值就像

0.012323
0.054544
0.0234243
etc..

我在任务管理器中看到的 CPU 使用率大约是 5%、10%、60% 等。我怎样才能得到这样的价值?

只需乘以 100。您将得到百分比形式的结果。单击 here 获取 javadoc。

您必须将它乘以 100 并转换为整数,请查看 JavaDocs :

Returns the "recent cpu usage" for the whole system. This value is a double in the [0.0,1.0] interval. A value of 0.0 means that all CPUs were idle during the recent period of time observed, while a value of 1.0 means that all CPUs were actively running 100% of the time during the recent period being observed. All values betweens 0.0 and 1.0 are possible depending of the activities going on in the system. If the system recent cpu usage is not available, the method returns a negative value.

请注意您系统上的 CPU 数量,因为它代表了您系统上所有可用的 CPU。

看看这个帮助方法,将您获得的值缩放为百分比:

 public static short getLoadAndScaleToPercent(Method method, OperatingSystemMXBean osMxBean) {
        if (method != null) {
            try {
                double load = (double) method.invoke(osMxBean);
                if (load >= 0) {
                    return (short) (load * 100);
                }
            } catch (Throwable t) {
                return -1;
            }
        }
        return -1;
    }