http://stackoverflow.com/questions/47177/how-to-monitor-the-computers-cpu-memory-and-disk-usage-in-java
package getcpu;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
*
* @author bert
*/
public class GetCPU {
public static void main(String[] args) {
new GetCPU().printUsage();
}
private void printUsage() {
//初始化OperatingSystemMXBean
OperatingSystemMXBean operatingSystemMXBean =
ManagementFactory.getOperatingSystemMXBean();
//取出operatingSystemMXBean裡面所有的Method
//(getCommittedVirtualMemorySize 等...)
for (Method method : operatingSystemMXBean.getClass()
.getDeclaredMethods()) {
//一定要允許method被存取,否則會出錯
method.setAccessible(true);
//method開頭是getxxxx,並且是Public method
if (method.getName().startsWith("get")
&& Modifier.isPublic(method.getModifiers())) {
Object value;
try {
//取得method的值
value = method.invoke(operatingSystemMXBean);
} catch (Exception e) {
value = e;
}
//輸出method名稱以及method值
System.out.println(method.getName() + " = " + value);
}
}
}
}
在win7下執行
若是把
method.setAccessible(true);改成
method.setAccessible(false);
則會發生以下錯誤
很可惜的getProcessCpuLoad 與getSystemCpuLoad 皆為-1,
文件上這麼說:
Returns: the "recent cpu usage" for the whole system; a negative value if not available.
也就是無法成功取得,所以回傳-1,即使用管理者身份執行Netbeans也一樣。
接下來我們試試看在OpenSuse 11.4上跑看看。
在OpenSuse 11.4 上是可以正常取出CPU使用率的~^^。
關於OperatingSystemMXBean,可以參考以下連結。
英文的
https://docs.oracle.com/javase/7/docs/jre/api/management/extension/com/sun/management/OperatingSystemMXBean.html#getProcessCpuLoad()
中文的說明
http://nothing.tw/JDK_API_1_6/java/lang/management/OperatingSystemMXBean.html
沒有留言:
張貼留言