一、目录
- Runtime类说明
- Runtime对象的常用方法
Runtime类说明:
- 运行时类(只是类名的直译),并不是getClass()方法拿到的处于运行时状态的类。
- 每个Java应用程序都有一个Runtime类实例,使应用程序能够与其运行的环境相连接。
- 可以通过Runtime类的静态方法getRuntime方法获取当前运行环境的Runtime类的对象。
- 应用程序不能创建自己的Runtime类实例。也就是说不能new一个Runtime出来,它是Java程序一运行,其运行环境就自然产生了。
- void gc() 运行垃圾回收器
System.gc()实际上等效于调用Runtime.getRuntime().gc()
- void exit(int status) 终止当前正在运行的Java虚拟机
- Process exec(String command, …) 在单独的进程中执行指定的字符串命令。
其中Process类有一个destory()方法:
- void destory() 杀掉子进程,也就是终止当前Process对象所表示的程序。
package com.javaruntime;
import java.io.IOException;
public class TestRuntime {
public static void main(String[] args) throws IOException, InterruptedException {
// 1. 拿到当前程序的运行时环境——获的Runtime对象
Runtime rn = Runtime.getRuntime();
// 2. 执行一个命令所表示的程序——打开记事本
// 3. Process对象ps,就表示这个记事本程序
Process ps = rn.exec("notepad");
Thread.sleep(1000);
// 4. 关闭打开的这个记事本的程序
ps.destroy();
}
}