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