首先创建一个测试的对象 RefrenceStuduet 类,重写toString方法
public class RefrenceStuduet {
private String name;
private int age;
public RefrenceStuduet(String name, int age) {
this.age = age;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "学生姓名:"+this.name+" 年龄:"+this.age;
}
}
然后编写测试代码:
public class Refrence {
public static void main(String... args) {
RefrenceStuduet studentA = new RefrenceStuduet("AA",1);
RefrenceStuduet studentB = new RefrenceStuduet("BB",2);
RefrenceStuduet studentC = new RefrenceStuduet("CC",3
);
//强引用strongStudentA
RefrenceStuduet strongStudentA = studentA;
//软引用softStudentB
SoftReference<RefrenceStuduet> softStudentB = new SoftReference<>(studentB);
//弱引用weekStudentC
WeakReference<RefrenceStuduet> weekStudentC = new WeakReference<>(studentC);
//直接弱引用
WeakReference<RefrenceStuduet> weekStudentD = new WeakReference<>(new RefrenceStuduet("DD",4));
//引用都变为null
studentA = null;
studentB = null;
studentC = null;
//gc之前 输出RefrenceStuduet的toString方法的内容
System.out.println("Before gc...");
System.out.println(String.format("strongA = %sn, softB = %s, weakC = %s, weakD = %s", strongStudentA, softStudentB.get(), weekStudentC.get(), weekStudentD.get()));
System.out.println("Run GC...");
//执行系统gc
System.gc();
//gc之后输出
System.out.println("After gc...");
System.out.println(String.format("strongA = %s, softB = %s, weakC = %s, weakD = %s", strongStudentA, softStudentB.get(), weekStudentC.get(), weekStudentD.get()));
}
}
运行结果:
Before gc...
strongA = 学生姓名:AA 年龄:1\n, softB = 学生姓名:BB 年龄:2\n, weakC = 学生姓名:CC 年龄:3\n, weakD = 学生姓名:DD 年龄:4\n
Run GC...
After gc...
strongA = 学生姓名:AA 年龄:1\n, softB = 学生姓名:BB 年龄:2\n, weakC = null\n, weakD = null\n
Java内存管理
本文通过创建RefrenceStuduet类并重写toString方法,演示了Java中不同类型的引用(强引用、软引用、弱引用)在内存管理中的行为差异。通过实例展示了在执行垃圾回收前后,各种引用指向的对象状态的变化。

1271

被折叠的 条评论
为什么被折叠?



