System類
System類的方法
No. | 方法 | 類型 | 描述 |
---|---|---|---|
1 | public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length) | 普通 | 數組粘貼操作 |
2 | public static long currentTimeMillis() | 普通 | 取得當前的日期時間,以long型數據返回 |
3 | public static void gc() | 普通 | 垃圾收集 |
currentTimeMillis()方法
例:觀察currentTimeMillis()方法的使用
package Project.Study.SystemClass;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test1 {
public static void main(String[]args){
//取得開始時間
long start=System.currentTimeMillis(); //currentTimeMillis()返回以毫秒爲單位的當前時間
String str="";
for(int x=0;x<30000;x++){
str+=x;
}
long end=System.currentTimeMillis(); //currentTimeMillis()返回以毫秒爲單位的當前時間
System.out.println("開始時間:"+start);
SimpleDateFormat start1 = new SimpleDateFormat("yyyy年-MM月dd日-HH時mm分ss秒");
Date date1 = new Date(start);
System.out.println(start1.format(date1));
System.out.println("結束時間:"+end);
SimpleDateFormat end2 = new SimpleDateFormat("yyyy年-MM月dd日-HH時mm分ss秒");
Date date2 = new Date(end);
System.out.println(end2.format(date2));
System.out.println("本次操作所花費的時間:"+(end-start));
}
}
//結果:
//開始時間:1585573645695
//2020年-03月30日-21時07分25秒
//結束時間:1585573646162
//2020年-03月30日-21時07分26秒
//本次操作所花費的時間:467(毫秒)
System類的gc()方法
該gc()方法不算一個新的操作方法,它是間接調用了Runtime類中的gc()方法,不表示一個重寫的方法。所以調用System.gc()和調用Runtime.getRuntime().gc()最終的效果是完全一樣的。
對象回收
如果要產生一個對象,可以通過構造方法處理一些對象產生時的操作,同樣當一個對象被回收時,我們也可以做一些收尾工作,可以通過finalize()方法實現,此方法由Object類定義。 對象回收方法如下:
protected void finalize() throws Throwable
例:對象回收操作
package Project.Study.SystemClass;
class Human{
public Human(){
System.out.println("一個健康的孩子出生了");
}
protected void finalize()throws Throwable{ //覆寫Object類方法
System.out.println("修仙活了200年,到時候了");
throw new Exception("此處即使拋出異常對象也不會產生任何影響");
}
}
public class Test2 {
public static void main(String[]args){
Human men=new Human(); //實例化新的對象
men=null; //產生垃圾
System.gc(); //手工處理垃圾收集
}
}
//結果:
//一個健康的孩子出生了
//修仙活了200年,到時候了
通過上程序我們可以看到,當一個對象的堆內存空間即將被回收後將自動調用finalize()方法,這樣就可以進行一些對象回收前的收尾工作。並且此方法即使產生任何異常或錯誤,也不會影響程序的正常執行。