Skip to content

System 类


常用方法

方法描述
System.currentTimeMillis()返回当前时间距离 1970-1-1 的毫秒数
System.arraycopy(源数组,源数组起始索引,目标数组,目标数组起始索引,拷贝长度)复制数组元素,比较适合拷贝到指定位置
System.exit()退出当前程序
System.gc()执行垃圾回收机制

currentTimeMillis()

返回当前时间距离 1970-1-1 的毫秒数

代码示例

java
public class main {
    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }
}

// 输出结果
1749372542217

arraycopy()

复制数组元素,比较适合拷贝到指定位置

使用方法:System.arraycopy(源数组,源数组起始索引,目标数组,目标数组起始索引拷贝长度

代码示例

java
import java.util.Arrays;

public class main {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4};
        int[] arr_new = new int[arr.length]; // 此时 arr_new 为 {0, 0, 0, 0}
        System.arraycopy(arr,0,arr_new,1,3);
        System.out.println(Arrays.toString(arr_new));
    }
}

// 输出结果
[0, 1, 2, 3]

代码分析

(1)源数组:arr

(2)源数组拷贝的起始位置:0

(3)目标数组:arr_new

(4)目标数组拷贝的起始位置:1

(5)拷贝长度:3

exit()

传入参数 0:表示正常退出

代码示例

java
public class main {
    public static void main(String[] args) {
        System.out.println("hello world");
        System.exit(0);
        System.out.println("程序继续执行...");
    }
}

// 输出结果
hello world

gc()

(1)主动触发垃圾回收机制,底层会默认调用 finalize()方法执行垃圾回收机制

(2)垃圾回收会在 JVM 内存使用达到某个阈值自动进行。调用 System.gc( ) 可以请求 JVM 进行垃圾回收,但这只是一个建议,JVM 不一定会立即执行垃圾回收操作

代码示例

java
public class finalize {
    public static void main(String[] args) {
        finals finals = new finals(18);
        finals = null;
        System.gc();
    }
}
class finals{
    int age;

    public finals(){

    }

    public finals(int age) {
        this.age = age;
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("调用finalize回收对象");
    }
}

// 输出
调用finalize回收对象