System概述
什么是System类
java.lang 包下的类 ,父类是Object
System类包含一些有用的类字段和方法,它不能被实例化
System类成员方法
System.gc() 运行垃圾回收器
System.exit(int status)终止当前正在运行的java虚拟机
System.currentTimeMillis()返回以毫秒为单位的当前时间
System.arraycopy() 拷贝数组
方法演示
- 垃圾清扫
public class clearRush {
public static void main(String[] args) {
for(int i = 0; i < 100; i++) {
new Demo();
System.gc(); //强行运行垃圾回收器
}
}
}
class Demo{
@Override
protected void finalize() {
System.out.println("垃圾被清扫了"); //被动运行垃圾回收器
}
}
- 终止java虚拟机
public class StopJvm {
public static void main(String[] args) {
System.exit(0); //非0状态是异常终止,退出java虚拟机
System.out.println("----------------"); //上面终止了jvm,所以结果什么也不输出
}
3. 获取当前时间毫秒值
public class clearRush {
public static void main(String[] args) {
long start = System.currentTimeMillis(); // 1秒等于1000毫秒
for(int i = 0; i < 1000; i++) {
System.out.println("*"); // 获取当前时间毫秒值
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
4 拷贝数组
public class ArrayCopy{
public static void main(String[] args) {
int[] src = { 11, 22, 33, 44, 55 };
int[] dest = new int[8];
for (int i = 0; i < dest.length; i++) {
System.out.print(dest[i] + " ");
}
System.out.println("\n上面是拷贝之前的dest数组中的元素");
System.arraycopy(src, 0, dest, 0, src.length); // 将数组src从0索引开始拷贝到dest数组0索引开始的位置,拷贝长度为src.length
for (int i = 0; i < dest.length; i++) {
System.out.print(dest[i] + " ");
}
}