您的位置:首页 > 编程语言 > Java开发

Java 父类和子类对象销毁实例

2013-12-02 14:32 471 查看
1)定义一个共享类Shared

使用long而不使用int,是为了防止溢出,refcount是共享类被其他类引用的次数,只要还有其他的类引用这个类,共享类就不会被GC回收。

package cn.javass.user;

public 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);

}

}

//重写toString方法

public String toString(){return "Shared"+id;};

}


2)定义一个组合类

package cn.javass.user;

public 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();

}

public String toString(){return "Composing" +id; };

}



3)定义引用计数类

package cn.javass.user;

public class ReferenceCounting {

public static void main(String[] args) {

Shared shared=new Shared();

Composing[] composings={new Composing(shared),new Composing(shared),new Composing(shared),new Composing(shared),new Composing(shared)};

for(Composing c:composings)

c.dispose();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐