java中强制启动垃圾回收器

     Java的垃圾回收器被执行的偶然性有时候也会给程序运行带来麻烦,比如说在一个对象成为垃圾时需要马上被释放,或者程序在某段时间内产生大量垃圾时,释放垃圾占据的内存空间似乎成了一件棘手的事情,如果垃圾回收器不被启动,finalize()方法也不会被调用。为此,Java里提供了一个System.gc()方法,使用这个方法可以强制启动垃圾回收器来会收垃圾,就象我们主动给环卫局打电话,通知他们提前来清扫垃圾的道理是一样的。我们将上面的程序作如下修改:

class Person

{

public void finalize()

{

     System.out.println("the object is going!");

}

public static void main(String [] args)

{

        new Person();

        new Person();

        new Person();

     System.gc();

     System.out.println("the program is ending!");

}

}

编译运行的结果如下:

the object is going!

the object is going!

the object is going!

the program is ending!

posted on 2010-05-16 10:05  傲视群雄  阅读(7066)  评论(0编辑  收藏  举报