同样的代码,将引用的对象置为null,为啥main方法里可以回收,android里button click触发的无法回收?

没有回收

 private void methodWeakTest() {
        String str = new String("value");

        WeakReference weakReference = new WeakReference<>(str);

        str = null;

        System.out.println("弱引用:WeakReference == GC回收前:" + weakReference.get());

        //系统GC垃圾回收
        System.gc();
        System.runFinalization();

        System.out.println("弱引用:WeakReference == GC回收后:" + weakReference.get());
    }

回收

public static  void main(String[] args){
        String str = new String("value");

        WeakReference weakReference = new WeakReference<>(str);

        str = null;

        System.out.println("弱引用:WeakReference == GC回收前:" + weakReference.get());

        //系统GC垃圾回收
        System.gc();
        System.runFinalization();

        System.out.println("弱引用:WeakReference == GC回收后:" + weakReference.get());
    }

0 条评论

发表回复

您的电子邮箱地址不会被公开。