1、概述
Runtime類封裝了運行時的環境。每一個 Java 應用程序都有一個 Runtime 類實例,使應用程序可以與其運行的環境相鏈接。
通常不能實例化一個Runtime對象,應用程序也不能建立本身的 Runtime 類實例,但能夠經過 getRuntime 方法獲取當前Runtime運行時對象的引用。
一旦獲得了一個當前的Runtime對象的引用,就能夠調用Runtime對象的方法去控制Java虛擬機的狀態和行爲。
當Applet和其餘不被信任的代碼調用任何Runtime方法時,經常會引發SecurityException異常。java
import java.lang.Runtime; public class RuntimeTest { public static void main(String[] args) { Runtime rt = Runtime.getRuntime(); System.out.println("處理器的數量:"+rt.availableProcessors()); } }
二、內存管理windows
Java提供了無用單元自動收集機制。經過totalMemory()和freeMemory()方法能夠知道對象的堆內存有多大,還剩多少。
Java會週期性的回收垃圾對象(未使用的對象),以便釋放內存空間。可是若是想先於收集器的下一次指定週期來收集廢棄的對象,能夠經過調用gc()方法來根據須要運行無用單元收集器。一個很好的試驗方法是先調用gc()方法,而後調用freeMemory()方法來查看基本的內存使用狀況,接着執行代碼,而後再次調用freeMemory()方法看看分配了多少內存。下面的程序演示了這個構想。安全
class MemoryDemo{ public static void main(String args[]){ Runtime r = Runtime.getRuntime(); long mem1,mem2; Integer someints[] = new Integer[1000]; System.out.println("Total memory is :" + r.totalMemory()); mem1 = r.freeMemory(); System.out.println("Initial free is : " + mem1); r.gc(); mem1 = r.freeMemory(); System.out.println("Free memory after garbage collection : " + mem1); //allocate integers for(int i=0; i<1000; i++) someints[i] = new Integer(i); mem2 = r.freeMemory(); System.out.println("Free memory after allocation : " + mem2); System.out.println("Memory used by allocation : " +(mem1-mem2)); //discard Intergers for(int i=0; i<1000; i++) someints[i] = null; r.gc(); //request garbage collection mem2 = r.freeMemory(); System.out.println("Free memory after collecting " + "discarded integers : " + mem2); } }
運行結果:(不一樣的機器不一樣時間運行的結果也不必定同樣):編碼
import java.lang.Runtime; import java.io.IOException; public class ExecTest { public static void main(String[] args) { Runtime rt = Runtime.getRuntime();
Process p = null; try{ p = rt.exec("notepad"); }catch(IOException e) { System.out.println("Execute error!"); } } }
exec()還有其餘幾種形式,例子中演示的是最經常使用的一種。ecec()方法返回Process對象後,在新程序開始運行後就可使用Process的方法了。能夠用destory()方法殺死子進程,也可使用waitFor()方法等待程序直到子程序結束,exitValue()方法返回子進程結束時返回的值。若是沒有錯誤,將返回0,不然返回非0。spa
下面是關於ecec()方法的例子的改進版本。例子被修改成等待,直到運行的進程退出:操作系統
class ExecDemoFini { public static void main(String args[]){ Runtime r = Runtime.getRuntime(); Process p = null; try{ p = r.exec("notepad"); p.waitFor(); } catch (Exception e) { System.out.println("Error executing notepad."); } System.out.println("Notepad returned " + p.exitValue()); } }
運行結果:(當關閉記事本後,會接着運行程序,打印信息)線程
當子進程正在運行時,能夠對標準輸入輸出進行讀寫。getOutputStream()方法和getInPutStream()方法返回對子進程的標準輸入和輸出。code