Java学习总结:33(System类)

System类

System类的方法

No.方法类型描述
1public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)普通数组粘贴操作
2public static long currentTimeMillis()普通取得当前的日期时间,以long型数据返回
3public 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()方法,这样就可以进行一些对象回收前的收尾工作。并且此方法即使产生任何异常或错误,也不会影响程序的正常执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值