日期:2014-05-20  浏览次数:20623 次

我写的一个finalize程序 怎么执行效果不对 ?
我为了验证finalize()的效果,写了一个程序,如下:
这个是主程序,调用System.gc(),
程序名:FinalizeTst.java
package   tst;

/**
  *   @file_name   FinalizeTst.java
  *   @author   (xddiao@cattsoft.com)
  *   @date   2007-6-8   下午08:46:42
  *   @description  
  *   @reviewed_by
  */
public   class   FinalizeTst     {


/**
  *   @method_name   main
  *   @author   xddiao@cattsoft.com
  *   @date   2007-6-8   下午08:46:44
  *   @description  
  *   @param   args  
  *   @reviewed_by
  */
public   static   void   main(String[]   args)   {
//   TODO   自动生成方法存根
Test   ft   =   new   Test();
ft.show();
System.gc();
System.out.println( "now   the   i   is   exist? "+   ft.getI().toString());
}



}


另外一个类Test.java如下:

程序名:Test.java

package   tst;


class   Test   {
private     Integer   i;

public   Test()
{
this.i=5;
}
protected   void   finalize(){
System.out.println( "gabbage   collected ");
}

protected   void   show(){
System.out.println( "the   i   is   : "   +this.i);
}

protected   Integer   getI()   {
return   this.i;
}
}

程序输出为:
the   i   is   :5
now   the   i   is   exist?5


按照我的想法:
应该会输出Test类中方法finalize()的打印内容,因为不是说,如果你调用System.gc()的时候,就会先调用finalize()的阿,为什么没有调用呢?

哪位高手给我解答一下!先多谢了!
   


------解决方案--------------------
测试发现,在垃圾回收前要检查是否存在无效对象,如果没有无限对象,则即使调用System.gc()也不会执行垃圾回收。
public static void main(String[] args) {
// TODO 自动生成方法存根
Test ft = new Test();//创建对象被引用,不被认为是垃圾
ft.show();
new Test();//创建了对象但是没有被引用,被认为是垃圾
System.gc();
System.out.println( "now the i is exist? "+ ft.getI().toString());
}

程序输出为:
the i is :5
gabbage collected
now the i is exist?5

------解决方案--------------------
Test ft = new Test();
ft.show();
ft=null;//注意这里要声明为null,这样在gc的时候才会被认为是垃圾
System.gc();
//System.out.println( "now the i is exist? "+ ft.getI().toString());
//这里你既然还在调用ft,那系统就认为ft还不是垃圾