强引用,软引用,弱引用,虚引用
测试对象
public class Obj {private final String name;public Obj(String name) {this.name = name;}@Overrideprotected void finalize() throws Throwable {System.out.println("执行finalize方法" + name);super.finalize();}@Overridepublic String toString() {return name;}}
import java.lang.ref.PhantomReference;import java.lang.ref.ReferenceQueue;import java.lang.ref.SoftReference;import java.lang.ref.WeakReference;public class Test {public static void main(String[] args) {// hardTest();softTest();// weakTest();// phanTest();}public static void hardTest() {Obj hard = new Obj("hard");hard = null;System.gc();System.out.println(hard);}public static void softTest() {SoftReference<Obj> soft = new SoftReference<Obj>(new Obj("soft"));System.gc();System.out.println(soft.get());}public static void weakTest() {WeakReference<Obj> weak = new WeakReference<Obj>(new Obj("soft"));System.gc();System.out.println(weak.get());}public static void phanTest() {ReferenceQueue<Obj> rq = new ReferenceQueue<Obj>();PhantomReference<Obj> phan = new PhantomReference<Obj>(new Obj("phan"), rq);//这里没有调用system.gc();System.out.println(phan.get());}}