JAVA获取JVM内存使用以及服务器CPU,硬盘使用方法

1,获取JVM内存方法:

 		int kb = 1024; 
	        // 可使用内存 
	        long totalMemory = Runtime.getRuntime().totalMemory() / kb; 
	        // 剩余内存 
	        long freeMemory = Runtime.getRuntime().freeMemory() / kb; 
	        // 最大可使用内存 
	        long maxMemory = Runtime.getRuntime().maxMemory() / kb; 
2,获取机器CPU使用率

       lunix 服务器获取方法

	public static double[] getCpuUsage(){
		   double cpuUsed = 0;
		   double idleUsed = 0.0;
		   double[] cpuarray = new double[2];
		   Runtime rt = Runtime.getRuntime();
		   Process p;
		   try {
			   p = rt.exec("top -b -n 1");
			   BufferedReader in = null;
		       in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			   String str = null;
			   int linecount = 0;
			   while ((str = in.readLine()) != null) {
			         linecount++;
				     if (linecount == 3) {
				      String[] s = str.split("%");
				      String idlestr = s[3];
				      String idlestr1[] = idlestr.split(" ");
				      idleUsed = Double.parseDouble(idlestr1[idlestr1.length-1]);
				      cpuUsed = 100-idleUsed;
				      cpuarray[0]=cpuUsed;
				      cpuarray[1]=idleUsed;
				      break;
				     }
			    }
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch (Exception e) {
				// TODO: handle exception
			}// call "top" command in linux 
				
		   return cpuarray;
			   
		} 
window服务器获取方法

 	   /** 
	     * 获得CPU使用率. 
	     * @return 返回cpu使用率 
	     * @author GuoHuang 
	     */
	    private static double getCpuRatioForWindows() { 
	        try { 
	            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)); 
	            Thread.sleep(CPUTIME); 
	            long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd)); 
	            if (c0 != null && c1 != null) { 
	                long idletime = c1[0] - c0[0]; 
	                long busytime = c1[1] - c0[1]; 
	                return Double.valueOf( 
	                        PERCENT * (busytime) / (busytime + idletime)) 
	                        .doubleValue(); 
	            } else { 
	                return 0.0; 
	            } 
	        } catch (Exception ex) { 
	            ex.printStackTrace(); 
	            return 0.0; 
	        } 
	    }
参考链接:

http://write.blog.csdn.net/postedit

http://naicj.iteye.com/blog/1299958

http://blog.csdn.net/longne/article/details/4518378  这链接包含各类JVM信息的方法

http://blog.csdn.net/chenzhanhai/article/details/6231789   这链接包含硬盘使用方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值