public class Test {
public static class A {
private B ref;
public void setB(B b) {
ref = b;
}
}
public static Class B {
private A ref;
public void setA(A a) {
ref = a;
}
}
public static void main(String args[]) {
…
start();
….
}
public static void start() { A a = new A();
B b = new B();
a.setB(b);
b = null; //
a = null;
…
}
}
b = null执行后b可以被垃圾回收
a = null执行后b可以被垃圾回收
a = null执行后a可以被垃圾回收
a,b必须在整个程序结束后才能被垃圾回收
类A和类B在设计上有循环引用,会导致内存泄露
a, b 必须在start方法执行完毕才能被垃圾回收