---
title: "java获得CPU、系统内存情况"
author: "hiwings"
date: "2011-11-20T23:43:20Z"
tags: []
categories: ["开源软件"]
slug: "java-cpu"
draft: false
lastmod: "2011-11-20T23:43:20Z"
id: 1269774
url: "https://hiwings.iteye.com/blog/1269774"
---

# java获得CPU、系统内存情况

 

JXM：Monitoring and Management Interface for the Java™ Platform

通过jmx可以监控vm内存使用,系统内存使用等

以下是网上某博客代码，特点是通过window和linux命令获得CPU使用率。 

 

Java代码

001. 利用java程序实现获取计算机cpu利用率和内存使用信息。
002. 创建一个Bean用来存贮要得到的信
003. public class MonitorInfoBean {
004. /\** 可使用内存. \*/
005. private long totalMemory;
006. /\**  剩余内存. \*/
007. private long freeMemory;
008. /\** 最大可使用内存. \*/
009. private long maxMemory;
010. /\** 操作系统. \*/
011. private String osName;
012. /\** 总的物理内存. \*/
013. private long totalMemorySize;
014. /\** 剩余的物理内存. \*/
015. private long freePhysicalMemorySize;
016. /\** 已使用的物理内存. \*/
017. private long usedMemory;
018. /\** 线程总数. \*/
019. private int totalThread;
020. /\** cpu使用率. \*/
021. private double cpuRatio;
022. public long getFreeMemory() {
023. return freeMemory;
024. }
025. public void setFreeMemory(long freeMemory) {
026. this.freeMemory = freeMemory;
027. }
028. public long getFreePhysicalMemorySize() {
029. return freePhysicalMemorySize;
030. }
031. public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
032. this.freePhysicalMemorySize = freePhysicalMemorySize;
033. }
034. public long getMaxMemory() {
035. return maxMemory;
036. }
037. public void setMaxMemory(long maxMemory) {
038. this.maxMemory = maxMemory;
039. }
040. public String getOsName() {
041. return osName;
042. }
043. public void setOsName(String osName) {
044. this.osName = osName;
045. }
046. public long getTotalMemory() {
047. return totalMemory;
048. }
049. public void setTotalMemory(long totalMemory) {
050. this.totalMemory = totalMemory;
051. }
052. public long getTotalMemorySize() {
053. return totalMemorySize;
054. }
055. public void setTotalMemorySize(long totalMemorySize) {
056. this.totalMemorySize = totalMemorySize;
057. }
058. public int getTotalThread() {
059. return totalThread;
060. }
061. public void setTotalThread(int totalThread) {
062. this.totalThread = totalThread;
063. }
064. public long getUsedMemory() {
065. return usedMemory;
066. }
067. public void setUsedMemory(long usedMemory) {
068. this.usedMemory = usedMemory;
069. }
070. public double getCpuRatio() {
071. return cpuRatio;
072. }
073. public void setCpuRatio(double cpuRatio) {
074. this.cpuRatio = cpuRatio;
075. }
076. }
077. 之后，建立bean的接口
078. public interface IMonitorService {
079. public MonitorInfoBean getMonitorInfoBean() throws Exception;
080. }
081. 然后，就是最关键的，得到cpu的利用率，已用内存，可用内存，最大内存等信息。
082. import java.io.InputStreamReader;
083. import java.io.LineNumberReader;
084. import sun.management.ManagementFactory;
085. import com.sun.management.OperatingSystemMXBean;
086. import java.io.\*;
087. import java.util.StringTokenizer;
088. /\**
089. * 获取系统信息的业务逻辑实现类.
090. * @author GuoHuang
091. \*/
092. public class MonitorServiceImpl implements IMonitorService {
093. private static final int CPUTIME = 30;
094. private static final int PERCENT = 100;
095. private static final int FAULTLENGTH = 10;
096. private static final File versionFile = new File("/proc/version");
097. private static String linuxVersion = null;
098. /\**
099. * 获得当前的监控对象.
100. * @return 返回构造好的监控对象
101. * @throws Exception
102. * @author GuoHuang
103. \*/
104. public MonitorInfoBean getMonitorInfoBean() throws Exception {
105. int kb = 1024;
106. // 可使用内存
107. long totalMemory = Runtime.getRuntime().totalMemory() / kb;
108. // 剩余内存
109. long freeMemory = Runtime.getRuntime().freeMemory() / kb;
110. // 最大可使用内存
111. long maxMemory = Runtime.getRuntime().maxMemory() / kb;
112. OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
113. .getOperatingSystemMXBean();
114. // 操作系统
115. String osName = System.getProperty("os.name");
116. // 总的物理内存
117. long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
118. // 剩余的物理内存
119. long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
120. // 已使用的物理内存
121. long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb
122. .getFreePhysicalMemorySize())
123. / kb;
124. // 获得线程总数
125. ThreadGroup parentThread;
126. for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
127. .getParent() != null; parentThread = parentThread.getParent())
128. ;
129. int totalThread = parentThread.activeCount();
130. double cpuRatio = 0;
131. if (osName.toLowerCase().startsWith("windows")) {
132. cpuRatio = this.getCpuRatioForWindows();
133. }
134. else {
135. cpuRatio = this.getCpuRateForLinux();
136. }
137. // 构造返回对象
138. MonitorInfoBean infoBean = new MonitorInfoBean();
139. infoBean.setFreeMemory(freeMemory);
140. infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);
141. infoBean.setMaxMemory(maxMemory);
142. infoBean.setOsName(osName);
143. infoBean.setTotalMemory(totalMemory);
144. infoBean.setTotalMemorySize(totalMemorySize);
145. infoBean.setTotalThread(totalThread);
146. infoBean.setUsedMemory(usedMemory);
147. infoBean.setCpuRatio(cpuRatio);
148. return infoBean;
149. }
150. private static double getCpuRateForLinux(){
151. InputStream is = null;
152. InputStreamReader isr = null;
153. BufferedReader brStat = null;
154. StringTokenizer tokenStat = null;
155. try{
156. System.out.println("Get usage rate of CUP , linux version: "+linuxVersion);
157. Process process = Runtime.getRuntime().exec("top -b -n 1");
158. is = process.getInputStream();
159. isr = new InputStreamReader(is);
160. brStat = new BufferedReader(isr);
161. if(linuxVersion.equals("2.4")){
162. brStat.readLine();
163. brStat.readLine();
164. brStat.readLine();
165. brStat.readLine();
166. tokenStat = new StringTokenizer(brStat.readLine());
167. tokenStat.nextToken();
168. tokenStat.nextToken();
169. String user = tokenStat.nextToken();
170. tokenStat.nextToken();
171. String system = tokenStat.nextToken();
172. tokenStat.nextToken();
173. String nice = tokenStat.nextToken();
174. System.out.println(user+" , "+system+" , "+nice);
175. user = user.substring(0,user.indexOf("%"));
176. system = system.substring(0,system.indexOf("%"));
177. nice = nice.substring(0,nice.indexOf("%"));
178. float userUsage = new Float(user).floatValue();
179. float systemUsage = new Float(system).floatValue();
180. float niceUsage = new Float(nice).floatValue();
181. return (userUsage+systemUsage+niceUsage)/100;
182. }else{
183. brStat.readLine();
184. brStat.readLine();
185. tokenStat = new StringTokenizer(brStat.readLine());
186. tokenStat.nextToken();
187. tokenStat.nextToken();
188. tokenStat.nextToken();
189. tokenStat.nextToken();
190. tokenStat.nextToken();
191. tokenStat.nextToken();
192. tokenStat.nextToken();
193. String cpuUsage = tokenStat.nextToken();
194. System.out.println("CPU idle : "+cpuUsage);
195. Float usage = new Float(cpuUsage.substring(0,cpuUsage.indexOf("%")));
196. return (1-usage.floatValue()/100);
197. }
198. } catch(IOException ioe){
199. System.out.println(ioe.getMessage());
200. freeResource(is, isr, brStat);
201. return 1;
202. } finally{
203. freeResource(is, isr, brStat);
204. }
205. }
206. private static void freeResource(InputStream is, InputStreamReader isr, BufferedReader br){
207. try{
208. if(is!=null)
209. is.close();
210. if(isr!=null)
211. isr.close();
212. if(br!=null)
213. br.close();
214. }catch(IOException ioe){
215. System.out.println(ioe.getMessage());
216. }
217. }
218. /\**
219. * 获得CPU使用率.
220. * @return 返回cpu使用率
221. * @author GuoHuang
222. \*/
223. private double getCpuRatioForWindows() {
224. try {
225. String procCmd = System.getenv("windir")
226. + "\\\\system32\\\\wbem\\\\wmic.exe process get Caption,CommandLine,"
227. + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
228. // 取进程信息
229. long\[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
230. Thread.sleep(CPUTIME);
231. long\[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
232. if (c0 != null && c1 != null) {
233. long idletime = c1\[0] - c0\[0];
234. long busytime = c1\[1] - c0\[1];
235. return Double.valueOf(
236. PERCENT * (busytime) / (busytime + idletime))
237. .doubleValue();
238. } else {
239. return 0.0;
240. }
241. } catch (Exception ex) {
242. ex.printStackTrace();
243. return 0.0;
244. }
245. }
246. /\**
247. * 读取CPU信息.
248. * @param proc
249. * @return
250. * @author GuoHuang
251. \*/
252. private long\[] readCpu(final Process proc) {
253. long\[] retn = new long\[2];
254. try {
255. proc.getOutputStream().close();
256. InputStreamReader ir = new InputStreamReader(proc.getInputStream());
257. LineNumberReader input = new LineNumberReader(ir);
258. String line = input.readLine();
259. if (line == null || line.length() &lt; FAULTLENGTH) {
260. return null;
261. }
262. int capidx = line.indexOf("Caption");
263. int cmdidx = line.indexOf("CommandLine");
264. int rocidx = line.indexOf("ReadOperationCount");
265. int umtidx = line.indexOf("UserModeTime");
266. int kmtidx = line.indexOf("KernelModeTime");
267. int wocidx = line.indexOf("WriteOperationCount");
268. long idletime = 0;
269. long kneltime = 0;
270. long usertime = 0;
271. while ((line = input.readLine()) != null) {
272. if (line.length() &lt; wocidx) {
273. continue;
274. }
275. // 字段出现顺序：Caption,CommandLine,KernelModeTime,ReadOperationCount,
276. // ThreadCount,UserModeTime,WriteOperation
277. String caption = Bytes.substring(line, capidx, cmdidx - 1)
278. .trim();
279. String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
280. if (cmd.indexOf("wmic.exe") &gt;= 0) {
281. continue;
282. }
283. // log.info("line="+line);
284. if (caption.equals("System Idle Process")
285. || caption.equals("System")) {
286. idletime += Long.valueOf(
287. Bytes.substring(line, kmtidx, rocidx - 1).trim())
288. .longValue();
289. idletime += Long.valueOf(
290. Bytes.substring(line, umtidx, wocidx - 1).trim())
291. .longValue();
292. continue;
293. }
294. kneltime += Long.valueOf(
295. Bytes.substring(line, kmtidx, rocidx - 1).trim())
296. .longValue();
297. usertime += Long.valueOf(
298. Bytes.substring(line, umtidx, wocidx - 1).trim())
299. .longValue();
300. }
301. retn\[0] = idletime;
302. retn\[1] = kneltime + usertime;
303. return retn;
304. } catch (Exception ex) {
305. ex.printStackTrace();
306. } finally {
307. try {
308. proc.getInputStream().close();
309. } catch (Exception e) {
310. e.printStackTrace();
311. }
312. }
313. return null;
314. }
315. /\**     测试方法.
316. * @param args
317. * @throws Exception
318. * @author GuoHuang
319. \*/
320. public static void main(String\[] args) throws Exception {
321. IMonitorService service = new MonitorServiceImpl();
322. MonitorInfoBean monitorInfo = service.getMonitorInfoBean();
323. System.out.println("cpu占有率=" + monitorInfo.getCpuRatio());
324. System.out.println("可使用内存=" + monitorInfo.getTotalMemory());
325. System.out.println("剩余内存=" + monitorInfo.getFreeMemory());
326. System.out.println("最大可使用内存=" + monitorInfo.getMaxMemory());
327. System.out.println("操作系统=" + monitorInfo.getOsName());
328. System.out.println("总的物理内存=" + monitorInfo.getTotalMemorySize() + "kb");
329. System.out.println("剩余的物理内存=" + monitorInfo.getFreeMemory() + "kb");
330. System.out.println("已使用的物理内存=" + monitorInfo.getUsedMemory() + "kb");
331. System.out.println("线程总数=" + monitorInfo.getTotalThread() + "kb");
332. }
333. }
334. 其中，Bytes类用来处理字符串
335. public class Bytes {
336. public static String substring(String src, int start\_idx, int end\_idx){
337. byte\[] b = src.getBytes();
338. String tgt = "";
339. for(int i=start\_idx; i&lt;=end\_idx; i++){
340. tgt +=(char)b\[i];
341. }
342. return tgt;
343. }
344. }