第三阶段 JAVA常见对象的学习

System类

System类包含一些有用的字段和方法,他不能被实例化

//用于垃圾回收public static void gc()//终止正在运行的java虚拟机。参数用作状态码,根据惯例,非0表示异常终止public static void exit(int status)//System.out.println(System.currentTimeMillis());//返回从1970年1月1日到现在时间的毫秒数(协调时间)public static currentTimeMills()public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)//src - 源数组。 //srcPos - 源数组中的起始位置。 //dest - 目标数组。 //destPos - 目的地数据中的起始位置。 //length - 要复制的数组元素的数量。 

arraycopy方法的使用案例

int[] arr = {11, 22, 33, 44, 55};int[] arr2 = {6, 7, 8, ,9 ,10};System.arraycopy(arr, 1, arr2, 2, 2);System.out.println(Arrays.toString(arr));System.out.println(Arrays.toString(arr2));//运行结果[11, 22, 33, 44, 55][6, 7, 22, 33, 10]

currentTimeMills()使用案例

package cn.bwh_02_currenTimeMillis;public class SystemDemo {    public static void main(String[] args) {        //统计这段程序运行时间        long start = System.currentTimeMillis();        for (int x = 0; x < 10000; x++){            System.out.println("Hello" + x);        }        long end = System.currentTimeMillis();        System.out.println("共耗时" + (end - start) + "毫秒");    }}//运行结果Hello9997Hello9998Hello9999共耗时79毫秒

System.gc() 可用于垃圾回收.当使用System.gc() 回收某个对象所占用的内存之前,通过要求程序调用适当的方法来清理资源,在没有明确指定资源清理的情况下,Java提高了默认机制来清理该对象的资源,就是调用object类的finalize()方法,finalize()方法的作用是释放一个对象占用的内存空间时会被JVM调用.而子类重写该方法, 就可以清理对象占用的资源,该方法没有链式调用, 所以必须手动实现。

从程序结果上可以发现执行system.gc() 前系统会自动调用finalize() 方法清除对象占有的资源。通过super.finalize()可以实现从下到上的方法调用,即先释放自己的资源,再释放父类的资源。

但是不要在程序中频繁的调用垃圾回收,因为每一次执行垃圾回收jvm都会强制启动垃圾回收器运行,就会耗费更多的系统资源会与正常的Java程序运行争抢资源,只有在执行大量的对象的释放才调用垃圾回收最好。

package cn.bwh_01_gc;public class Student {    private String name;    private int age;    public Student() {    }    public Student(String name, int age) {        this.name = name;        this.age = age;    }    @Override    protected void finalize() throws Throwable {        System.out.println("当前对象被回收了" + this);        super.finalize();    }}
package cn.bwh_01_gc;public class GcDemo {    public static void main(String[] args) {        Student s = new Student("admin", 20);        System.out.println(s);        //让s不再指定堆内存,成为了垃圾        s = null;        System.gc();    }}//运行结果cn.bwh_01_gc.Student@1b6d3586当前对象被回收了cn.bwh_01_gc.Student@1b6d3586

结尾:

如果内容中有什么不足,或者错误的地方,欢迎大家给我留言提出意见, 蟹蟹大家 !^_^

如果能帮到你的话,那就来关注我吧!(系列文章均会在公众号第一时间更新)

在这里的我们素不相识,却都在为了自己的梦而努力 ❤

一个坚持推送原创Java技术的公众号:理想二旬不止