Java常用類庫--Runtime類
1、認識Runtime類



2、得到JVM的信息
public class RuntimeDemo01{ public static void main(String args[]){ Runtime run = Runtime.getRuntime(); // 通過Runtime類的靜態方法進行實例化操作 System.out.println("JVM最大內存量:" + run.maxMemory()) ; // 觀察最大的內存,根據機器的不同,環境也會有所不同 System.out.println("JVM空閑內存量:" + run.freeMemory()) ; // 取得程序運行的空閑內存 String str = "Hello " + "World" + "!!!" +"\t" + "Welcome " + "To " + "MLDN" + "~" ; System.out.println(str) ; for(int x=0;x<1000;x++){ str += x ; // 循環修改內容,會產生多個垃圾 } System.out.println("操作String之後的,JVM空閑內存量:" + run.freeMemory()) ; run.gc() ; // 進行垃圾收集,釋放空間 System.out.println("垃圾回收之後的,JVM空閑內存量:" + run.freeMemory()) ; } };
3、Runtime與Process類

public class RuntimeDemo02{ public static void main(String args[]){ Runtime run = Runtime.getRuntime() ; // 取得Runtime類的實例化對象 try{ run.exec("notepad.exe") ; // 調用本機程序,此方法需要異常處理 }catch(Exception e){ e.printStackTrace() ; // 打印異常信息 // System.out.println(e) ; } } };


public class RuntimeDemo03{ public static void main(String args[]){ Runtime run = Runtime.getRuntime() ; // 取得Runtime類的實例化對象 Process p = null ; // 定義進程變量 try{ p = run.exec("notepad.exe") ; // 調用本機程序,此方法需要異常處理 }catch(Exception e){ e.printStackTrace() ; // 打印異常信息 // System.out.println(e) ; } try{ Thread.sleep(5000) ; // 讓此線程存活5秒 }catch(Exception e){ } p.destroy() ; // 結束此進程 } };
4、總結

最後更新:2017-04-03 14:53:45