Java—System類入門學習

第三階段 JAVA常見對象的學習

System類

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

//用於垃圾回收
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()使用案例jvm

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) + "毫秒");
    }
}

//運行結果
Hello9997
Hello9998
Hello9999
共耗時79毫秒

System.gc() 可用於垃圾回收.當使用System.gc() 回收某個對象所佔用的內存以前,經過要求程序調用適當的方法來清理資源,在沒有明確指定資源清理的狀況下,Java提升了默認機制來清理該對象的資源,就是調用object類的finalize()方法,finalize()方法的做用是釋放一個對象佔用的內存空間時會被JVM調用.而子類重寫該方法, 就能夠清理對象佔用的資源,該方法沒有鏈式調用, 因此必須手動實現。ide

從程序結果上能夠發現執行system.gc() 前系統會自動調用finalize() 方法清除對象佔有的資源。經過super.finalize()能夠實現從下到上的方法調用,即先釋放本身的資源,再釋放父類的資源。 學習

可是不要在程序中頻繁的調用垃圾回收,由於每一次執行垃圾回收jvm都會強制啓動垃圾回收器運行,就會耗費更多的系統資源會與正常的Java程序運行爭搶資源,只有在執行大量的對象的釋放才調用垃圾回收最好。this

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

結尾:

若是內容中有什麼不足,或者錯誤的地方,歡迎你們給我留言提出意見, 蟹蟹你們 !^_^spa

若是能幫到你的話,那就來關注我吧!(系列文章均會在公衆號第一時間更新)code

在這裏的咱們素不相識,卻都在爲了本身的夢而努力 ❤

一個堅持推送原創Java技術的公衆號:理想二旬不止對象

img

相關文章
相關標籤/搜索