System 类初探

System 类

操作方法

取得当前的系统时间

currentTemiMillis()

public static long currenTimeMillis() ;
  • 实例:

统计某些操作的执行时间

public class TestDemo {
	public static void main(String [] args) {
		long start = System.currentTimeMillis(); // 开始时间
		String str = "" ;
		for (int x = 0; x < 30000 ; x++) {
			str += x ; 
		}
		long end = System.currentTimeMillis(); //结束时间
		System.out.println("Time = " + (end - start));// 单位ms
	}
}
// 执行结果:(单位:ms)
Time = 2246

system.gc()

  • System类的GC方法,并不是一个新的GC方法,而是调用了Runtime类中的GC方法
public static void gc() ;
  • 引出:

    对象产生会调用类的构造方法执行一些处理操作,但是如果一个产生的对象被GC回收了,而Java提供了一个可以在对象被GC回收之前执行代码块的方法——finzlize()方法

finalize() 方法

protected void finalize() throws Throwable 

Throwable:无乱任何错误,都执行完程序

class Member {
	public Member() {
		System.out.println("open");
	}
	@Override
	protected void finalize() throws Throwable {
		System.out.println("end");
		throw new Exception("……");	// 抛出异常
	}
}

public class TestDemo {
	public static void main(String [] args) {
		Member men = new Member() ;
		men = null ; // 对象成为了垃圾
		System.gc(); // 手工GC垃圾处理
	}
}

程序执行:men = null 成为了垃圾对象,然后 GC手工回收,触发finalize(),执行方法规定的代码块程序。(相当于是在GC垃圾回收前调用finzlize())

——

构造方法是供对象初始化时使用的,而 finalize()方法是供对象被GC回收之前使用的。

  • final、finally、finalize三者的区别
  • final:Java关键字,定义不能被继承的类、不能被覆写的方法和常量
  • finally:Java关键字,异常的统一出口
  • finalize:内置方法,public static void finzlize() throws Throwable;程序对象GC回收前的执行方法,即使出现异常也不会导致程序中断
posted @ 2019-06-26 23:09  Mirror王宇阳  阅读(134)  评论(0编辑  收藏  举报