← 返回首页
JavaSE系列教程(五十五)
发表时间:2020-02-02 15:04:08
讲解Runtime工具类。

每个java程序在运行时相当于启动了一个JVM进程,每个JVM进程都对应一个RunTime实例。此实例是JVM负责实例化的,所以我们不能实例化一个RunTime对象,只能通过getRuntime() 获取当前运行的Runtime对象的引用。一旦得到了一个当前的Runtime对象的引用,就可以调用Runtime对象的方法去查看Java虚拟机的状态以及控制虚拟机的行为。

通过查看Runtime类的源码,我们发现Runtime拥有一个静态初始化对象——饿汉模式。

    private static Runtime currentRuntime = new Runtime();

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance
     * methods and must be invoked with respect to the current runtime object.
     *
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() {
        return currentRuntime;
    }

Runtime类常用方法

1)getRuntime()方法,返回与当前Java应用关联的runtime对象。 2)availableProcessors()方法,返回Java虚拟机可用的处理器数。 3)exec(String command)方法,在一个单独的进程中执行指定的命令。 4)load(String command)方法,可以加载动态链接库,如linux下的so文件,win下的dll文件。

通过一个实例理解以上方法:

Runtime runtime = Runtime.getRuntime();//获得runtime对象
String [] cmd={"cmd","/C","javac HelloWorld.java"};
System.out.println(runtime.availableProcessors());//返回处理器数量
runtime.exec("notepad.exe");//打开记事本应用程序
runtime.exec(cmd); //打开控制台窗口,调用javac命令编译java源程序。生成字节码文件。
runtime.load("C:/Windows/System32/crypt32.dll");//加载系统加密动态链接库。