易百教程

181、gc()方法的作用是什么?

gc()方法用于调用垃圾收集器进行清理处理。 此方法可在 SystemRuntime 类中找到。该函数显式地使 Java 虚拟机释放未使用对象所占用的空间,以便可以利用或重用它。 请参考以下示例,以更好地理解 gc() 方法如何调用垃圾收集器。


public class TestGarbage1 {

    public void finalize() {
        System.out.println("object is garbage collected");
    }

    public static void main(String args[]) {
        TestGarbage1 s1 = new TestGarbage1();
        TestGarbage1 s2 = new TestGarbage1();
        s1 = null;
        s2 = null;
        System.gc();
    }
}

运行结果如下:

object is garbage collected
object is garbage collected