一. 说明
- 代表程序所在的运行环境
- Runtime是一个单例类
二. 常用的方法
方法名 | 说明 |
---|---|
public static Runtime getRuntime() | 返回与当前Java应用程序关联的运行时对象 |
public void exit(int status) | 终止当前运行的虚拟机 |
public int availableProcessors() | 返回Java虚拟机可用的处理器数 |
public long totalMemory() | 返回Java虚拟机中的内存总量 |
public long freeMemory() | 返回Java虚拟机中的可用内存 |
public Process exec(String command) | 启动某个程序,并返回代表该程序的对象 |
三. 使用
1. public static Runtime getRuntime()
要注意的是,Runtime是一个单例类,他的构造器被私有化了,那么如果要创建对象则需要直接调用getRuntime方法。
Runtime r = Runtime.getRuntime();
2. public void exit(int status)
这个方法大家并不陌生,在System类中也有这样的一个方法,但实际上System类中的exit方法其实调用的就是Runtime中的exit方法。
r.exit(0);
3. public int availableProcessors()
public class RuntimeTest {
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
System.out.println(r.availableProcessors());
}
}
通过它,我们可以知道java虚拟机最多能用的处理器数目
4. public long totalMemory()
返回当前java程序占用的内存数量
public class RuntimeTest {
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
System.out.println(r.totalMemory() / 1024.0 + "KB");
System.out.println(r.totalMemory() / 1024.0 / 1024.0 + "MB");
}
}
5. public long freeMemory()
还有多少空闲的内存够java虚拟机使用?
public class RuntimeTest {
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
System.out.println(r.freeMemory() / 1024.0 / 1024.0 + "MB");
}
}
6. public Process exec(String command)
启动某个程序,并返回代表该程序的对象
public class RuntimeTest {
public static void main(String[] args) throws IOException {
Runtime r = Runtime.getRuntime();
r.exec("D:\\soft\\XMind.exe");
}
}
他就会帮我打开XMind这个程序
public class RuntimeTest {
public static void main(String[] args) throws IOException {
Runtime r = Runtime.getRuntime();
r.exec("QQ");
}
}
那如果说我们将QQ添加到了环境变量当中,就可以直接使用QQ打开了。
既然能够打开程序,那么也一定能关闭程序。
public class RuntimeTest {
public static void main(String[] args) throws IOException, InterruptedException {
Runtime r = Runtime.getRuntime();
Process p = r.exec("D:\\soft\\XMind.exe");
Thread.sleep(5000); //让程序在这里暂停5s后继续往下走
p.destroy();
}
}
首先我们知道,打开了程序后会创建这个程序的对象,这个时候我们将它赋给Process变量p,接着,为了防止一打开程序立马就关闭了,我们在打开程序与关闭程序之间通过Thread.sleep让它等待5s后再执行p.destroy方法关闭程序。