Java中的垃圾回收

                        Java中的垃圾回收

protect void finalize() 来源于Object类
          Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

 

public static void gc() 来源于System类
    Runs the garbage collector.

代码
// 本类演示java的垃圾回收机制。
public class GarbageDemo {
int index;// 保存对象的索引值。
static int count = 0;// 记录当前产生了多少个对象。

public GarbageDemo() {
count
++;
System.out.println(
"" + count + "个对象产生了");
setIndex(count);
}

public void setIndex(int index) {
this.index = index;
}

protected void finalize() {
System.out.println(
"" + index + "个对象被回收了");
}

public static void main(String[] args) {
new GarbageDemo();
new GarbageDemo();
new GarbageDemo();
new GarbageDemo();
// 产生了四个GarbageDemo对象,因为new 一个对象之后,
// 没有将这个对象的引用赋值给某一个变量,因此,这些对象
// 所占用的内存没有被任何的变量所引用,因此这些对象就是一个垃圾了。

System.gc();
// 显示的运行垃圾收集器。没有这一句代码是看不见对象被回收的效果的。
}
}
第1个对象产生了
第2个对象产生了
第3个对象产生了
第4个对象产生了
第3个对象被回收了
第4个对象被回收了
第2个对象被回收了
第1个对象被回收了

posted @ 2010-12-21 13:02  meng72ndsc  阅读(157)  评论(0编辑  收藏  举报