package com.wb.demo.util; import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.util.LinkedList; import java.util.List; public class PhantoReference {
//容器 final static List<Object> list = new LinkedList<>();
// final static ReferenceQueue<TTT> queue = new ReferenceQueue<>(); public static void main(String[] args) { PhantomReference<TTT> phantomReference = new PhantomReference(new TTT(), queue); new Thread(() -> { while (true) {
//一直添加数据 list.add(new Byte[1024 * 1024]); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } System.out.println(phantomReference.get()); } }).start(); new Thread(() -> { while (true) {
//被回收时,放入queue Reference poll = queue.poll(); if (poll != null) { System.out.println("--------- 虚引用对象被jvm回收了 --------------" + poll); } } }).start(); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }
标签:java,Thread,queue,引用,import,new,poll From: https://www.cnblogs.com/wangbiaohistory/p/18632451