Runtime类介绍
Runtime类用于表示虚拟机运行时的状态, 用于封装JVM虚拟机进程.
每次启动虚拟机都对应一个Runtime实例, 且只有一个实例.
因为该类采用单例模式设计, 对象不可以直接实例化. 所以要想获得一个Runtime实例, 只能通过如下方式
Runtime rt = Runtime.getRuntime();
获取当前虚拟机的相关信息
1 public static void main(String[] args) { 2 // 获取Runtime实例对象 3 Runtime rt = Runtime.getRuntime(); 4 System.out.println("处理器个数: "+rt.availableProcessors()); 5 System.out.println("空闲内存M数: "+rt.freeMemory()/1024/1024); 6 System.out.println("最大可用内存M数: "+rt.maxMemory()/1024/1024); 7 }
exec()方法执行dos命令
1 public static void main(String[] args) { 2 Runtime rt = Runtime.getRuntime(); 3 try { 4 rt.exec("notepad.exe"); 5 } catch (IOException e) { 6 e.printStackTrace(); 7 } 8 }
exec()方法返回一个Process对象, 该对象表示操作系统的一个进程, 通过该对象可以对产生的新进程进行管理
1 public static void main(String[] args) throws IOException, InterruptedException { 2 // 获取Runtime实例对象 3 Runtime rt = Runtime.getRuntime(); 4 // 得到表示进程的Process对象 5 Process process = rt.exec("notepad.exe"); 6 // 程序休眠3秒 7 Thread.sleep(3000); 8 // kill进程 9 process.destroy(); 10 }