| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 906 人关注过本帖
标题:下面程序的含义(refcount为什么等于5)
只看楼主 加入收藏
ltf119
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2010-6-25
结帖率:50%
收藏
 问题点数:0 回复次数:2 
下面程序的含义(refcount为什么等于5)
程序代码:
//: polymorphism/ReferenceCounting.java
// Cleaning up shared member objects.
import static net.mindview.util.Print.*;  //为将System.out.println() 转换为print()引入的包

class Shared {
  private int refcount = 0;
  private static long counter = 0;
  private final long id = counter++;
  public Shared() {
    print("Creating " + this);
  }
  public void addRef() { refcount++; }
  protected void dispose() {
    if(--refcount == 0)
      print("Disposing " + this);
  }
  public String toString() { return "Shared " + id; }
}

class Composing {
  private Shared shared;
  private static long counter = 0;
  private final long id = counter++;
  public Composing(Shared shared) {
    print("Creating " + this);
    this.shared = shared;
    this.shared.addRef();
  }
  protected void dispose() {
    print("disposing " + this);
    shared.dispose();
  }
  public String toString() { return "Composing " + id; }
}

public class ReferenceCounting {
  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();
  }
}
程序代码:
//Output:
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
*///:~
//为什么从程序在运行中refcount=5,另外共享对象是什么意思?
搜索更多相关主题的帖子: refcount 含义 
2010-08-12 10:58
shellingford
Rank: 9Rank: 9Rank: 9
等 级:贵宾
威 望:19
帖 子:228
专家分:1348
注 册:2010-8-9
收藏
得分:0 

java中对象的传递是传引用的,Composing的构造函数中执行了shared的addref方法。将refcount+1了
由于 composing数组中new Composing时传入的对象是同一个shared,所以这个shared的refcount一共加了5次1

换句话说5个Composing对象中的shared所引用的是同一个对象。

如果把
Composing[] composing = { new Composing(shared),
      new Composing(shared), new Composing(shared),
      new Composing(shared), new Composing(shared) };
改成
Composing[] composing = { new Composing(new Shared()),
      new Composing(new Shared()), new Composing(new Shared()),
      new Composing(new Shared()), new Composing(new Shared()) };

那么就有5个Shared对象,每个对象的refcount就是1而不是5了
2010-08-12 12:19
ltf119
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2010-6-25
收藏
得分:0 
回复 2楼 shellingford
您回答的太帅了,看来您是这方面的高手,不介意的话可以让我加你的qq吗?本人是初学者,可能还有很多地方要向您请教。我的qq是:514921274。
2010-08-12 12:29
快速回复:下面程序的含义(refcount为什么等于5)
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.018343 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved