Java Runtime
類用於與Java運行時環境交互。Java Runtime
類提供了執行進程,調用GC,獲取總記憶體和可用記憶體等的方法。一個java應用程式只有一個java.lang.Runtime
類實例。
Runtime.getRuntime()
方法返回Runtime
類的單例實例。
Java Runtime類的重要方法
編號 | 方法 | 描述 |
---|---|---|
1 | public static Runtime getRuntime() |
返回Runtime 類的實例。 |
2 | public void exit(int status) |
終止當前的虛擬機。 |
3 | public void addShutdownHook(Thread hook) |
註冊新的鉤子線程。 |
4 | public Process exec(String command)throws IOException |
在單獨的進程中執行給定的命令。 |
5 | public int availableProcessors() |
返回可用的處理器的編號。 |
6 | public long freeMemory() |
返回JVM中的可用記憶體量。 |
7 | public long totalMemory() |
返回JVM中的總記憶體量。 |
Java Runtime exec()方法
public class Runtime1{
public static void main(String args[])throws Exception{
Runtime.getRuntime().exec("notepad");//will open a new notepad
}
}
如何在Java執行關閉電腦系統
可以使用shutdown -s
命令關閉系統。 對於Windows操作系統,需要提供完整的關閉命令路徑,例如:c:\\\\Windows\\\\System32\\\\shutdown
。
在這裏可以使用-s switch
來關閉系統,-r switch
來重啟系統,-t switch
來指定時間延遲。
public class Runtime2{
public static void main(String args[])throws Exception{
Runtime.getRuntime().exec("shutdown -s -t 0");
}
}
如何在Java中關閉Windows系統
public class Runtime2{
public static void main(String args[])throws Exception{
Runtime.getRuntime().exec("c:\\\\Windows\\\\System32\\\\shutdown -s -t 0");
}
}
如何在Java中重啟Windows系統
public class Runtime3{
public static void main(String args[])throws Exception{
Runtime.getRuntime().exec("shutdown -r -t 0");
}
}
Java Runtime availableProcessors()方法
public class Runtime4{
public static void main(String args[])throws Exception{
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
Java Runtime freeMemory()和totalMemory()方法
在給定的程式中,創建10000
個實例後,空閒記憶體將小於之前的空閒記憶體。 但是在gc()
調用之後,將獲得更多的可用記憶體。
package com.zaixian;
public class MemoryTest {
public static void main(String args[]) throws Exception {
Runtime r = Runtime.getRuntime();
System.out.println("Total Memory: " + r.totalMemory());
System.out.println("Free Memory: " + r.freeMemory());
for (int i = 0; i < 10000; i++) {
new MemoryTest();
}
System.out.println("After creating 10000 instance, Free Memory: " + r.freeMemory());
System.gc();
System.out.println("After gc(), Free Memory: " + r.freeMemory());
}
}
執行上面示例代碼,得到以下結果:
Total Memory: 128974848
Free Memory: 126930016
After creating 10000 instance, Free Memory: 126930016
After gc(), Free Memory: 127734760
上一篇:
Java垃圾收集
下一篇:無