Java中的Runtime類

來源:互聯網
上載者:User

標籤:class   system   win   collect   代碼   通過   str   ring   程式   

Runtime類描述了虛擬機器一些資訊。該類採用了單例設計模式,可以通過靜態方法 getRuntime()擷取Runtime類執行個體。下面示範了擷取虛擬機器的記憶體資訊:

 1 package Main; 2   3 public class Main 4 { 5     public static void main(String[] args) throws Exception 6     { 7         Runtime runtime = Runtime.getRuntime(); 8         System.out.println("total memory:"+runtime.totalMemory()/(1024*1024) + "M"); 9         System.out.println("max memory:" + runtime.maxMemory()/(1024*1024) + "M");10         System.out.println("free memory:" + runtime.freeMemory()/(1024*1024) + "M");11         System.out.println("Main Done//~~");12     }13 }

輸出結果:

total memory:230Mmax memory:3403Mfree memory:226MMain Done//~~

Runtime類提供gc()方法,用於釋放Java虛擬機器的一些無用空間。gc是garbage collection的縮寫,就是記憶體回收的意思。

 1 package Main; 2   3 public class Main 4 { 5     public static void main(String[] args) throws Exception 6     { 7         Runtime runtime = Runtime.getRuntime(); 8         runtime.gc(); 9         System.out.println("Main Done//~~");10     }11 }

Runtime類可以調用原生一些可執行程式,並且建立進程。exec(String cmd)方法可以開啟一個可執行程式,下面代碼示範了開啟windows記事本程式並5秒後關閉。

 1 package Main; 2   3 public class Main 4 { 5     public static void main(String[] args) throws Exception 6     { 7         Runtime runtime = Runtime.getRuntime(); 8         Process process = runtime.exec("notepad"); 9         Thread.sleep(1000*5);10         process.destroy();11         System.out.println("Main Done//~~");12     }13 }

 

Java中的Runtime類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.