JDK1.8获取CPU利用率
时间: 2023-10-13 08:04:54 浏览: 152
获取CPU使用率
可以使用Java Management Extensions(JMX)来获取CPU利用率。具体步骤如下:
1. 获取Java虚拟机的MBeanServer对象。
```java
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
```
2. 获取操作系统的ObjectName对象。
```java
ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
```
3. 调用MBeanServer的方法获取操作系统的属性值,包括CPU利用率。
```java
AttributeList list = mbs.getAttributes(name, new String[]{"ProcessCpuLoad", "SystemCpuLoad"});
if (list.isEmpty()) return Double.NaN;
Attribute att = (Attribute) list.get(0);
Double value = (Double) att.getValue();
// CPU利用率为value * 100.0
```
完整示例代码如下:
```java
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.MBeanServer;
import javax.management.ObjectName;
public class CPUMonitor {
private static final int SLEEP_TIME = 500;
public static void main(String[] args) throws Exception {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
Method method = mbs.getClass().getMethod("getOperatingSystemMXBean");
OperatingSystemMXBean os = (OperatingSystemMXBean) method.invoke(mbs);
long prevUpTime = os.getProcessCpuTime();
long prevSystemTime = System.nanoTime();
while (true) {
Thread.sleep(SLEEP_TIME);
long upTime = os.getProcessCpuTime();
long systemTime = System.nanoTime();
double cpuUsage = (double) (upTime - prevUpTime) / (systemTime - prevSystemTime);
cpuUsage *= os.getAvailableProcessors();
cpuUsage *= 100.0;
prevUpTime = upTime;
prevSystemTime = systemTime;
System.out.println("CPU Usage: " + String.format("%.2f%%", cpuUsage));
}
}
}
```
阅读全文