标签:
package com.mufeng.theeighthchapter; class Shared { private int refcount = 0; private static long counter = 0; private final long id = counter++; public Shared() { // TODO Auto-generated constructor stub System.out.println("Creating " + this); } public void addRef() { refcount++; } protected void dispose() { if (--refcount == 0) { System.out.println("Disposing " + this); } } @Override public String toString() { // TODO Auto-generated method stub return "Shared " + id; } } class Composing { private Shared shared; private static long counter = 0; private final long id = counter++; public Composing(Shared shared) { // TODO Auto-generated constructor stub System.out.println("creating " + this); this.shared = shared; this.shared.addRef(); } protected void dispose() { System.out.println("disposing " + this); shared.dispose(); } @Override public String toString() { // TODO Auto-generated method stub return "Composing " + id; } } public class ReferenceCount { public static void main(String[] args) { Shared shared = new Shared(); Composing[] composing = { new Composing(shared), new Composing(shared), new Composing(shared), new Composing(shared), new Composing(shared) }; for (Composing c : composing) { c.dispose(); } } }
Creating Shared 0 creating Composing 0 creating Composing 1 creating Composing 2 creating Composing 3 creating Composing 4 disposing Composing 0 disposing Composing 1 disposing Composing 2 disposing Composing 3 disposing Composing 4 Disposing Shared 0
标签:
原文地址:http://blog.csdn.net/u013693649/article/details/51915189