我正在使用此代码获取一些值
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
method.setAccessible(true);
if (method.getName().startsWith("get")
&& Modifier.isPublic(method.getModifiers())) {
Object value;
try {
value = method.invoke(operatingSystemMXBean);
} catch (Exception e) {
value = e;
} // try
System.out.println("\n \t ");
System.out.println( method.getName() + " = " + value);
}
}
输出:
getFreeSwapSpaceSize = 413728768
getProcessCpuLoad = -1.0
getProcessCpuTime = 1029606600
getSystemCpuLoad = 0.31576507895572437
getCommittedVirtualMemorySize = 48242688
getFreePhysicalMemorySize = 207011840
getTotalPhysicalMemorySize = 2147483647
getTotalSwapSpaceSize = 4294967295
但我想分别获取每个数据,上面的输出值存储在value
中,并存储在该单个对象中。我想在摇摆中使用它,以便在每个按钮单击时我分别得到上面的值。截至目前,只需按一下按钮,我就能得到上述所有信息,但我希望它是分开的,例如:单独的物理内存总量,然后是系统CPU负载等...
如何修改上述程序以便我可以单独存储每个值?
答案 0 :(得分:0)
对于要放入UI的每个Button,将其创建为
Button b1 = new Button();
b1.setActionCommand("getTotalSwapSpace");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
try {
Method method = operatingSystemMXBean.getClass().getDeclaredMethod("getTotalSwapSpaceSize", null);
method.setAccessible(true);
Object value = method.invoke(operatingSystemMXBean, new Object[]{});
System.out.println(" Value = " + value);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
显示返回的值。更改了原始代码,试试这个..
答案 1 :(得分:0)
对于CPU使用OperatingSystemMXBean类
OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
int availableProcessors = operatingSystemMXBean.getAvailableProcessors();
long prevUpTime = runtimeMXBean.getUptime();
long prevProcessCpuTime = operatingSystemMXBean.getProcessCpuTime();
double cpuUsage;
try
{
Thread.sleep(500);
}
catch (Exception ignored) { }
operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long upTime = runtimeMXBean.getUptime();
long processCpuTime = operatingSystemMXBean.getProcessCpuTime();
long elapsedCpu = processCpuTime - prevProcessCpuTime;
long elapsedTime = upTime - prevUpTime;
cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * availableProcessors));
System.out.println("Java CPU: " + cpuUsage);
对于内存使用java.lang.management中的Runtime类
long total = Runtime.getRuntime().totalMemory();
long used = Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();