Java 强,弱,软,虚 引用

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

public class TestGC {
    /**
     *
     * 软引用   当内存满的时候,才会回收软引用指向的对象
     * 弱引用  每次进行垃圾回收时,不论内存是否满,都是回收弱引用指向的对象
     *
     * @param args
     */
    public static void main(String[] args) {
        String str = new String("asdasd"); //强引用
        SoftReference<String> softReference = new SoftReference<String>(str); //软引用
        str = null; // 去掉强引用
        System.gc(); //垃圾回收器进行回收
        System.out.println(softReference.get()); // asdasd

        String abc = new String("asdas"); // 强引用
        WeakReference<String> weakReference = new WeakReference<String>(abc);//弱引用
        abc = null;// 去掉强引用
        System.gc(); // 垃圾回收器进行回收
        System.out.println(weakReference.get()); // null
    }
}

  

posted @ 2019-09-22 16:53  lick  阅读(129)  评论(0编辑  收藏  举报