import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
/**
* @Author hrong
* @Description
**/
public class Test {
public static void main(String[] args) throws Exception {
boolean ibmVendor = System.getProperty("java.vendor").contains("IBM");
int totalMb = 0;
int freeMb = 0;
Class<?> beanClass;
OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
if (ibmVendor) {
beanClass = Class.forName("com.ibm.lang.management.OperatingSystemMXBean");
} else {
beanClass = Class.forName("com.sun.management.OperatingSystemMXBean");
}
Method getTotalPhysicalMemorySize = beanClass.getDeclaredMethod("getTotalPhysicalMemorySize");
Method getFreePhysicalMemorySize = beanClass.getDeclaredMethod("getFreePhysicalMemorySize");
totalMb = (int) (Long.valueOf(getTotalPhysicalMemorySize.invoke(bean).toString()) / 1024 / 1024);
freeMb = (int) (Long.valueOf(getFreePhysicalMemorySize.invoke(bean).toString()) / 1024 / 1024);
System.out.println(String.format("总内存:%dmb", totalMb));
System.out.println(String.format("剩余内存:%dmb", freeMb));
int cores = Runtime.getRuntime().availableProcessors();
System.out.println(String.format("总核数:%d", cores));
}
}
获取当前电脑的总内存量、可用内存量、总核数
最新推荐文章于 2022-12-08 10:12:07 发布