193649-1737200209e7de

Runtime类

  • 代表程序运行环境
  • Runtime是一个单例类

image-20250119162824306

查看源码可以看到,Runtime的构造器是私有的。并且有一个Runtime类型的静态成员变量currentRuntime,提供了一个getRuntime的静态函数返回了这个对象。

Runtime的常用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public static void main(String[] args) throws IOException, InterruptedException {
// 获取Runtime对象
Runtime rt = Runtime.getRuntime();
// 终止当前的虚拟机
// rt.exit(0);

// 获取虚拟机能够使用的CPU数
int count = rt.availableProcessors();
System.out.println(count);

// 获取java虚拟机中的总内存数量
long total = rt.totalMemory();
System.out.println(total / 1024 / 1024 + "MB");

// 查看java虚拟机中可用内存量
long free = rt.freeMemory();
System.out.println(free / 1024 / 1024 + "MB");

// 启动某个程序
Process process = rt.exec("E:\\QQMusic\\QQMusic.exe");

// 五秒后关闭程序
Thread.sleep(5000);
process.destroy();
}