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   這鏈接包含硬盤使用方法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章