示例代码 1
简单的相互引用;
public class Main {
public static void main(String[] args) throws Exception {
A a = new A();
B b = new B();
a.b = b;
b.a =a;
a=null;
b=null;
for(int i = 0;i10){
System.gc();
}
Thread.sleep(1000);
System.err.println("i = "+i);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
class A{
public B b;
}
class B{
public A a;
}
i 小于 10 时
i 大于10 时
说明 A B 二个类 都被回收了。
但是我们经常在不经意间就使用了相互引用,但是在释放时,有只会释放一个,
示例2
public class Main {
public static void main(String[] args) throws Exception {
A a = new A();
B b = new B();
a.b = b;
b.a =a;
a=null;
//b=null;
for(int i = 0;i10){
System.gc();
}
Thread.sleep(1000);
System.err.println("i = "+i);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
class A{
public B b;
}
class B{
public A a;
}
当 i 大于 10 之后,执行来多次 GC,A B 类 实例都存在,不会被GC 回收。
避免在实际运用中使用相互引用,多使用 传参 方式来 获取 类 实例 信息。
示例3:
public class Main {
public static void main(String[] args) throws Exception {
HashMaptmp = new HashMap<>();
tmp.put("1",new Classz());
tmp.put("2",new Classz());
tmp.put("3",new Classz());
tmp.put("4",new Classz());
tmp.put("5",new Classz());
tmp.put("6",new Classz());
tmp.put("7",new Classz());
tmp.put("8",new Classz());
tmp.put("9",new Classz());
tmp.put("10",new Classz());
for(int i = 0;i20)
{
System.gc();
}
Thread.sleep(1000);
System.err.println("i = "+i);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
class Classz {
/**班级里面的 学生*/
Student s1;
Student s2;
Student s3;
public Classz()
{
this.s1 = new Student(this);
this.s2 = new Student(this);
this.s3 = new Student(this);
}
}
class Student
{
/**学生所属班级*/
Classz c;
public Student(Classz c1)
{
this.c = c1;
}
public Classz getC(){
return c;
}
}
i < 20
i >= 20