多语言展示
当前在线:1417今日阅读:86今日分享:14

java获取windowscpu使用率方法

java不是系统级的语言,所以获取系统信息需要用一些系统命令,这里就分享怎么用java获取cpu信息
工具/原料

java

方法/步骤
1

第一步:判断系统,linux,windons,mac等等系统使用命令和方法都不一样。代码如下:// 操作系统 String osName = System.getProperty('os.name');

2

第二步:获取系统内存信息,代码如下:// 可使用内存 long totalMemory = Runtime.getRuntime().totalMemory() / kb; // 剩余内存 long freeMemory = Runtime.getRuntime().freeMemory() / kb; // 最大可使用内存 long maxMemory = Runtime.getRuntime().maxMemory() / kb;

3

第三步:获取cpu信息,命令和代码如下:String procCmd = System.getenv('windir')         + '//system32//wbem//wmic.exe process get Caption,CommandLine,'         + 'KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount'; // 取进程信息 long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));

5

第五步:构造对象,对返回的结果进行封装,代码如下:// 构造返回对象 MonitorInfoBean infoBean = new MonitorInfoBean(); infoBean.setFreeMemory(freeMemory); infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize); infoBean.setMaxMemory(maxMemory); infoBean.setOsName(osName); infoBean.setTotalMemory(totalMemory); infoBean.setTotalMemorySize(totalMemorySize); infoBean.setTotalThread(totalThread); infoBean.setUsedMemory(usedMemory); infoBean.setCpuRatio(cpuRatio);

6

第六步:MonitorInfoBean 实体类代码如下:@Data public class MonitorInfoBean {     /** *//** 可使用内存. */     private long totalMemory;     /** *//** 剩余内存. */     private long freeMemory;     /** *//** 最大可使用内存. */     private long maxMemory;     /** *//** 操作系统. */     private String osName;     /** *//** 总的物理内存. */     private long totalMemorySize;     /** *//** 剩余的物理内存. */     private long freePhysicalMemorySize;     /** *//** 已使用的物理内存. */     private long usedMemory;     /** *//** 线程总数. */     private int totalThread;     /** *//** cpu使用率. */     private double cpuRatio;  }

7

第七步:运行结果展示,如图:

8

第八步:此放不了网盘地址,要的留言

推荐信息