arthas1982
发贴: 11
积分: 0
|
于 2004-10-09 09:47
只有在当前线程消亡了时候,此线程的类变量才被JVM收集。dorrenchen仁兄的功底好深啊,小弟一时没有看懂。小弟写了个自己的,大家看看 import java.lang.ref.WeakReference;
public class Garbage{ public Object a; public Object b; public Object c; public WeakReference aR; //WeakReference 不会影响JVM对他所引用的对象的收集 public WeakReference bR; public WeakReference cR; public Garbage(){ a = new Object(); b = new Object(); c = new Object(); aR = new WeakReference(a); bR = new WeakReference(b); cR = new WeakReference(c); } public void run(){ System.out.println("run() Begin!"); print(); a = b; System.out.println("execute a = b"); print(); a = c; System.out.println("execute a = c"); print(); c = null; System.out.println("execute c = null"); print(); a = null; System.out.println("execute a = null"); print(); System.out.println("run() End!"); } public void print(){ System.out.println("a :"+aR.get());//如果a:后是null,则说明他被回收了 System.out.println("b :"+bR.get()); System.out.println("c :"+cR.get()); } } public class Test {
public static void main(String[] args) { Garbage g = new Garbage(); g.run(); } }
|