Java之Runtime类简介说明
下文笔者将讲述Runtime类的简介说明,如下所示
Runtime类的简介
Runtime类: 是JDK封装运行时的环境(如:JVM虚拟机的行为和状态) 每个Java应用程序都有一个Runtime类实例 使应用程序能够与其运行的环境相连接 注意事项: 1.不能实例化一个Runtime对象,应用程序也不能创建自己Runtime类实例 只能通过getRuntime方法获取当前Runtime运行时对象的引用 2.Applet和其他不被信任的代码调用任何Runtime方法时, 会引起SecurityException异常
API方法
public native int availableProcessors(); public native long freeMemory(); public native long totalMemory(); public native long maxMemory(); 例: Runtime rt = Runtime.getRuntime(); System.out.println("处理器数量:" + rt.availableProcessors()); //处理器数量:4 System.out.println("空闲内存数:" + rt.freeMemory() / 1024 / 1024 + "mb"); //空闲内存数:800mb System.out.println("总内存数:" + rt.totalMemory() / 1024 / 1024 + "mb"); //总内存数:1024mb System.out.println("可用最大内存数:" + rt.maxMemory() / 1024 / 1024 + "mb"); //可用最大内存数:176mb
System的使用场景
使用totalMemory()和freeMemory()方法 可知道对象的堆内存有多大
Runtime的第二个功能:运行其它程序
例:打开计算器public static void main(String[] args) throws IOException { Runtime rt = Runtime.getRuntime(); //rt.exec("notepad.exe"); //打开记事本 备注:.exe可以省略 下同 Process process = rt.exec("calc.exe");//打开计算器 System.out.println(process); //Process[pid=8108, exitValue="not exited"] }例:打开记事本
public static void main(String[] args) throws IOException, InterruptedException { Runtime rt = Runtime.getRuntime(); Process process = rt.exec("notepad.exe"); //打开记事本 备注:.exe可以省略 下同 //Process process = rt.exec("calc.exe");//打开计算器 process.waitFor(); //阻塞 等到子进程执行结束 System.out.println("字进行执行完事了~~~"); process.destroyForcibly(); //强制杀死子进程 destroy }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。