java中跟踪共享对象的调用数量

xiaoxiao2021-02-28  103

package polymorphism; /** * 跟踪共享对象调用的数量 */ public class ReferenceCounting { public static void main(String[] args) { Shared shared = new Shared(); Compsing[] compsings = {new Compsing(shared), new Compsing(shared), new Compsing(shared), new Compsing(shared), new Compsing(shared)}; for (Compsing c : compsings) c.dispose(); } } class Shared { //参考数量 private int refcount = 0; //统计实例创建的数量 private static long counter = 0; //每创建一次实例就记一次数 private final long id = counter++; public Shared() { System.out.println("Creating" + this); } public void addRef() { refcount++; } protected void dispose() { if (--refcount == 0) System.out.println("Disposing" + this); } public String toString() { return "Shared " + id; } } class Compsing { private Shared shared; private static long counter = 0; private final long id = counter++; public Compsing(Shared shared) { System.out.println(this); System.out.println("Creatting" + this); this.shared = shared; this.shared.addRef(); } protected void dispose() { System.out.println("dispose" + this); shared.dispose(); } public String toString() { return "Compsing" + id; } } 说实话这段代码看着都有点似懂非懂的感觉,虽然读懂是什么意思~ 但是不知道为什么这样设计,勉强理解!
转载请注明原文地址: https://www.6miu.com/read-70158.html

最新回复(0)