Java中Runtime類詳細總結

Runtime類簡介

Java中,Runtime類提供了許多的API 來與java runtime environment進行交互,如:

  • 執行一個進程。
  • 調用垃圾回收。
  • 查看總內存和剩餘內存。

Runtime是單例的,可以通過Runtime.getRuntime()得到這個單例。

API列表

public static Runtime getRuntime() 返回單例的Runtime實例
public void exit(int status) 終止當前的虛擬機
public void addShutdownHook(Thread hook) 增加一個JVM關閉後的鉤子
public Process exec(String command)throws IOException 執行command指令,啓動一個新的進程
public int availableProcessors() 獲得JVM可用的處理器數量(一般爲CPU核心數)
public long freeMemory() 獲得JVM已經從系統中獲取到的總共的內存數【byte】
public long totalMemory() 獲得JVM中剩餘的內存數【byte】
public long maxMemory() 獲得JVM中可以從系統中獲取的最大的內存數【byte】

注:以上爲列舉的比較常見的一些方法,不完全。

經典案例

exec

    @Test
    public void testExec(){
        Process process = null;
        try {
            // 打開記事本
            process = Runtime.getRuntime().exec("notepad");
            Thread.sleep(2000);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }finally {
            if(process != null){
                process.destroy();
            }
        }
    }

獲取信息

    @Test
    public void testFreeMemory(){
        Runtime r = Runtime.getRuntime();
        System.out.println("處理器個數: " + r.availableProcessors());
        System.out.println("最大內存 : " + r.maxMemory());
        System.out.println("總內存 : " + r.totalMemory());
        System.out.println("剩餘內存: " + r.freeMemory());
        System.out.println("最大可用內存: " + getUsableMemory());

        for(int i = 0; i < 10000; i ++){
            new Object();
        }

        System.out.println("創建10000個實例之後, 剩餘內存: " + r.freeMemory());
        r.gc();
        System.out.println("gc之後, 剩餘內存: " + r.freeMemory());

    }
    /**
     * 獲得JVM最大可用內存 = 最大內存-總內存+剩餘內存
     */
    private long getUsableMemory() {
        Runtime r = Runtime.getRuntime();
        return r.maxMemory() - r.totalMemory() + r.freeMemory();
    }
處理器個數: 4
最大內存 : 3787980800
總內存 : 255328256
剩餘內存: 245988344
最大可用內存: 3778640888
創建10000個實例之後, 剩餘內存: 244650952
gc之後, 剩餘內存: 252594608

註冊鉤子線程

    @Test
    public void testAddShutdownHook() throws InterruptedException {
        Runtime.getRuntime().addShutdownHook(new Thread(()-> System.out.println("programming exit!")));
        System.out.println("sleep 3s");
        Thread.sleep(3000);
        System.out.println("over");
    }

3s之後,test方法結束,打印信息。

取消註冊鉤子線程

    @Test
    public void testRemoveShutdownHook() throws InterruptedException {
        Thread thread = new Thread(()-> System.out.println("programming exit!"));
        Runtime.getRuntime().addShutdownHook(thread);
        System.out.println("sleep 3s");
        Thread.sleep(3000);
        Runtime.getRuntime().removeShutdownHook(thread);
        System.out.println("over");
    }

終止!

    @Test
    public void testExit(){
        Runtime.getRuntime().exit(0);
        //下面這段 無事發生
        System.out.println("Program Running Check");
    }

參考閱讀

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