5.3 System和Runtime类

系列 - Java API
目录
本手册介绍了Java中System类和Runtime类的使用。System类提供了数组拷贝、获取当前时间、系统信息和垃圾回收等功能。Runtime类则用于获取虚拟机信息以及执行进程等操作。学生可以通过学习本手册了解这两个类的基本用法。
任务一:System类
1.1 拷贝数组
/**
* 拷贝数组
* System.arraycopy()
*/
public class Example10 {
public static void main(String[] args) {
int[] srcArray = {10 ,11, 12, 13, 14, 15, 16};
int[] toArray = {20, 21, 22, 23, 24, 25, 26, 27};
System.arraycopy(srcArray, 2, toArray, 3, 4);
System.out.println("拷贝后的数组元素为:");
for (int i = 0; i < toArray.length; i++) {
System.out.println("i : " + toArray[i]);
}
}
}
1.2 获取当前时间
/**
* 获取当前时间
*/
public class Example11 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
String test = "";
for (int i = 0; i < 100000; i ++) {
test += "test";
}
long endTime = System.currentTimeMillis();
System.out.println("程序运行的时间:" + (endTime - startTime) + "ms");
}
}
1.3 获取系统信息(了解内容)
import java.util.Enumeration;
import java.util.Properties;
/**
* 获取系统信息
*/
public class Example12 {
public static void main(String[] args) {
// 获取当前系统信息
Properties prop = System.getProperties();
Enumeration names = prop.propertyNames();
while (names.hasMoreElements()) {
String key = (String) names.nextElement();
String value = prop.getProperty(key);
System.out.println(key + "=" + value);
}
}
}
1.4 垃圾回收
/**
* 垃圾回收
*/
class Person {
String name;
public Person(String name) {
this.name = name;
}
public void finalize() {
System.out.println( name + " 要被回收啦!");
}
}
public class Example13 {
public static void main(String[] args) {
Person p1 = new Person("小明");
Person p2 = new Person("大王");
p1 = null;
p2 = null;
System.gc();
for (int i = 0; i < 1000000; i ++) {
// 为了延长程序运行的时间
}
}
}
运行结果:
任务二:Runtime类
2.1 获取虚拟机信息
/**
* 获取当前虚拟机信息
*/
public class Example14 {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.println("处理器个数:" + rt.availableProcessors());
System.out.println("空闲内存:" + rt.freeMemory()/1024/1024 + "MB");
System.out.println("虚拟机中的内存总量:" + rt.totalMemory()/1024/1024 + "MB");
System.out.println("最大可用内存:" + rt.maxMemory()/1024/1024 + "MB");
}
}
2.2 执行进程
public class Example15 {
public static void main(String[] args) {
Runtime rt = Runtime._getRuntime_();
try {
rt.exec("notepad.exe");
} catch (Exception e) {
System._out_.println(e.getMessage());
}
}
}
关闭打开的进程:
public class Example15 {
public static void main(String[] args) {
Runtime rt = Runtime._getRuntime_();
try {
Process process = rt.exec("notepad.exe");
Thread.sleep(3000);
process.destroy();
} catch (Exception e) {
System._out_.println(e.getMessage());
}
}
}