java.lang.Runtime類知多少?

1、概述

  • 每個java應用程序都包含一個Runtime類的實例,使應用程序能與其運行環境相連接(exec方法與運行環境進行交互);
  • 一般不能實例化Runtime(中文名:運行時)實例,應用程序也無法創建自身的Runtime實例,只能通過調用getRuntime方法獲得其Runtime對象的引用;
  • 一旦得到一個Runtime對象的引用,就可以調用Runtime對象的方法去控制java虛擬機的狀態和行爲;(問:虛擬機狀態和行爲都有哪些?)
  • 當Applet或者不被信任的代碼調用任何Runtime方法時,常常會引起SecurityException異常

2、API預覽(主要介紹exec方法,其他方法可查jdk)

  • exec(String command)
    在單獨的進程中執行指定的字符串命令。
  • exec(String[] cmdarray)
    在單獨的進程中執行指定命令和變量。
  • exec(String[] cmdarray, String[] envp)
    在指定環境的獨立進程中執行指定命令和變量。
  • exec(String[] cmdarray, String[] envp, File dir)
    在指定環境和工作目錄的獨立進程中執行指定的命令和變量。
  • exec(String command, String[] envp)
    在指定環境的單獨進程中執行指定的字符串命令。
  • exec(String command, String[] envp, File dir)
    在有指定環境和工作目錄的獨立進程中執行指定的字符串命令。

3、常見應用

public static void main(String[] args) {

    // 1、內存管理
    /**
     * Java提供了無用單元自動收集機制。通過totalMemory()和freeMemory()方法可以知道對象
     * 的堆內存有多大,還剩多少。Java會週期性的回收垃圾對象(未使用的對象),以便釋放內存空間。
     * 但是如果想先於收集器的下一次指定週期來收集廢棄的對象,可以通過調用gc()方法來根據需要運行
     * 無用單元收集器。一個很好的試驗方法是先調用gc()方法,然後調用freeMemory()方法來查看基
     * 本的內存使用情況,接着執行代碼,然後再次調用freeMemory()方法看看分配了多少內存。下面 的程序演示了這個構想。
     */
    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);
    // 分配整數數組空間
    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));
    // 分配的數組置空
    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);

    // 2、執行其他程序
    /**
     * 在安全的環境中,可以在多任務操作系統中使用Java去執行其他特別大的進程(也就是程序)。
     * ecec()方法有幾種形式命名想要運行的程序和它的輸入參數。ecec()方法返回一個
     * Process對象,可以使用這個對象控制Java程序與新運行的進程進行交互。ecec()方法 本質是依賴於環境。
     */
    Process p = null;
    try {
        p = r.exec("notepad"); // 開啓notepad子進程
        p.waitFor(1, TimeUnit.SECONDS); // 等待子進程結束後(設置等待1秒),方可繼續執行
        p.destroy(); // 關閉子進程
    } catch (Exception e) {
        System.out.println("Error executing notepad.");
    }
}

當子進程正在運行時,可以對標準輸入輸出進行讀寫。getOutputStream()方法和getInPutStream()方法返回對子進程的標準輸入和輸出。

以上大部分內容來自SUN公司的java.long.Runtime類的API文檔,相關代碼來《java核心技術》

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