`
只帅一次
  • 浏览: 34875 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java编程思想练习题-第5章练习11-finalize方法2

阅读更多

题目:修改前一个练习程序,让你的finalize方法总会被调用

分析:上一个例子中我们使用system.gc方法,但是偶尔会出现finalize方法不会被调用的情形。那是因为

System.gc(); 
//告诉垃圾收集器打算进行垃圾收集,而垃圾收集器进不进行收集是不确定的 

System.runFinalization(); 
//强制调用已经失去引用的对象的finalize方法 

 

所以如果用runFinalization方法的话,那finalize方法绝对会被调用。

public class test {
	
	@Override
	public void finalize(){
		System.out.println("start finalize  "+this);
	}
	public static void main(String[] args)  {
		test t=new test();
		t=null;
		System.gc();
		System.runFinalization();
	
	}
}

 注意的是,要先嗲用gc方法再调用runFinalization方法,

写道
System.gc(); hints the VM that it is probably time to activate the Thread doing to the Garbage Collection. So all the part of this sentence stands in the hint word. The finalizer are run according to the VM good will, generally speaking. This means they could be run or could not.
Invoking the System.runFinalization( ); force the VM to invoke on each instance the finalizer when it Garbage collects the Object referenced

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics