为了演示Java中
我期望的输出结果应该是这样的:
finalize()
方法的工作原理,该方法在对象即将销毁时被调用。我编写了以下程序。class counterTest{
public static int count;
public counterTest(){
count++;
}
}
public class finalize {
public static void main(String args[]){
counterTest obj1=new counterTest();
System.out.println("Number of objects :" + counterTest.count);
counterTest obj2=new counterTest();
System.out.println("Number of objects :" + counterTest.count);
Runtime rs=Runtime.getRuntime();
obj1=null;
obj2=null;
rs.gc();
}
protected void finalize(){
System.out.println("Program about to terminate");
counterTest.count--;
System.out.println("Number of objects :" + counterTest.count);
}
}
我期望的输出结果应该是这样的:
Number of objects :1
Number of objects :2
Program about to terminate
Number of objects :1
Program about to terminate
Number of objects :0
但我只得到了前两行的内容。因为我将对象引用设置为null,然后调用gc()
方法,所以我希望在finalize()
方法中编写的语句应该被显示。这是否意味着我们无法保证每次使用gc()
方法时都会调用finalize()
方法。