import java.lang.ref.WeakReference;
public class WeakReferenceTest {
public static void main(String[] args) throws InterruptedException {
WeakReference<String> wr1 = new WeakReference<String>(new String("弱引用,如果是对象,则遇到gc将被回收;如果是非对象,则不会被回收;"));
System.out.println(wr1.get());
System.gc();
System.out.println(wr1.get());
System.out.println("------------------------------------------------");
WeakReference<String> wr2 = new WeakReference<String>("弱引用,如果是对象,则遇到gc将被回收;如果是非对象,则不会被回收;");
System.out.println(wr2.get());
System.gc();
System.out.println(wr2.get());
System.out.println("------------------------------------------------");
WeakReference<Integer> wr3 = new WeakReference<Integer>(1);
System.out.println(wr3.get());
System.gc();
System.out.println(wr3.get());
System.out.println("------------------------------------------------");
WeakReference<Integer> wr4 = new WeakReference<Integer>(new Integer(1));
System.out.println(wr4.get());
System.gc();
System.out.println(wr4.get());
}
}
//输出结果:
弱引用,如果是对象,则遇到gc将被回收;如果是非对象,则不会被回收;
null
------------------------------------------------
弱引用,如果是对象,则遇到gc将被回收;如果是非对象,则不会被回收;
弱引用,如果是对象,则遇到gc将被回收;如果是非对象,则不会被回收;
------------------------------------------------
1
1
------------------------------------------------
1
null
WeakReference类详解
最新推荐文章于 2024-06-20 09:59:56 发布