package threaddemo;

import java.lang.ref.WeakReference;

public class WeakReferenceExample {

    public static void main(String[] args) {
        Object obj = new Object();

        //创建一个弱引用，指向该对象
        WeakReference<Object> weakRef = new WeakReference<>(obj);

        //手动调用垃圾回收
        System.gc();

        //检查弱引用是否被回收
        if (weakRef.get() == null) {
            System.out.println("Weak reference has been collected.");
        } else {
            System.out.println("Weak reference still exists.");
        }

        //清除强引用
        obj = null;

        if (weakRef.get() == null) {
            System.out.println("Weak reference has been collected.");
        } else {
            System.out.println("Weak reference still exists.");
        }

        //再次手动调用垃圾回收
        System.gc();

        //再次检查弱引用是否被回收
        if (weakRef.get() == null) {
            System.out.println("Weak reference has been collected.");
        } else {
            System.out.println("Weak reference still exists.");
        }
    }
}
