1.引入库
代码如下(示例):
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>6.2.2</version>
</dependency>
2.代码
代码如下(示例):
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
public class TestController {
public static void main(String[] args) throws InterruptedException {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
CentralProcessor processor = hal.getProcessor();
GlobalMemory memory = hal.getMemory();
// 第一次采样
long[] prevTicks = processor.getSystemCpuLoadTicks();
// 等待一段时间,通常是1秒
Thread.sleep(1000);
// 计算CPU负载百分比
double load = processor.getSystemCpuLoadBetweenTicks(prevTicks) * 100;
// 获取内存信息
long availableMemory = memory.getAvailable();
long totalMemory = memory.getTotal();
System.out.println("Processor Name: " + processor.getProcessorIdentifier().getName());
System.out.println("CPU Load: " + String.format("%.1f", load) + "%");
System.out.println("Available Memory: " + availableMemory / (1024 * 1024) + " MB");
System.out.println("Total Memory: " + totalMemory / (1024 * 1024) + " MB");
}
}