自动回收机制不是在程序运行结束就运行的,
而是当jvm虚拟机感觉内存比较紧张,须要回收的时候才会运行的.所以这样才会运行
public class  finalizeTest{
public void checkIn(){
}
public void finalize(){
System.out.print("the erroe");
}
public static void main(String[] args) 
{
for(int i=0;i<30000;i++)
{
finalizeTest test = new finalizeTest();
}
}
}

解决方案 »

  1.   

    1.楼上说法是错误的。
    2.
        Garbage Collector根据“需要”而决定销毁某些对象。并不是程序一退出马上就会被销毁。
    3.
        你可以调用垃圾收集器“System.gc();”,但调用的含义是“你要求系统来回收”,系统收到了这个请求,但系统是否真正的去回收,会根据线程繁忙程度来判断。如果线程正闲置,会响应你的请求。4.楼主的程序是不会被回收的。只要main方法没执行完,永远都不会被回收。原因很简单,在main方法内,“finalizeTest test = new finalizeTest();”后的“System.gc();”是要求系统去回收垃圾。系统线程此时显然有闲暇时间,经过判断,发现test仍然引用着TestGC对象。所以,不会去回收test。5.按上面的分析,把只要让test不在引用对象,对象会被立刻回收,当你调用System.gc()的时候。6.重新书写事例代码如下:
    public class  TestGC{
        public void finalize(){
                System.out.print("the erroe");
        }
        public static void main(String[] args)
        {
            TestGC test = new TestGC();
            test = new TestGC();
            test = null;
            System.gc();
            System.out.println("Hello World!");
        }
    }7.程序说明:
    test = null,让test失去了对new TestGC()的引用。new TestGC()对象没有任何人在引用。在你申请GC的时候,就被回收了。因为此时系统只运行你一个线程(还有其他后台辅助的),当然有空闲时间,于是立刻回收了你的。程序输出“the erroeHello World!”。8.同理,下面的代码,也会输出回收调用的结果。
    public class  TestGC{
        public void finalize(){
                System.out.print("the erroe");
        }
        public static void main(String[] args)
        {
            TestGC test = new TestGC();
            test = new TestGC();
            test = new TestGC();        System.gc();
            System.out.println("Hello World!");
        }
    }