作者yangpika (狗狗洋ˇ洋)
看板java
标题Re: [问题] 两个thread要reference到同一个object
时间Sat Feb 21 13:45:44 2009
感谢H45的方法 不过我没用
我看了一些关於Singleton的资料
写了底下的程式
public class controller {
private int test=5;
//假设这是thread要共用的值
private static controller control = new controller();
//避免使用者用new弄出多个instance
private controller(){}
public static controller getInstance(){
return control;
}
//避免使用者用clone弄出多个instance
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
//对要共用的值做加法
public void testAdd(int n){
test+=n;
System.out.println("test的值增加为"+test);
}
//得到要共用的值的大小
public int getTest(){
return test;
}
}
然後在thread那边这样写
public void run(){
System.out.println(this+","+obj.getTest());
obj.testAdd(10);
System.out.println(this+","+obj.getTest());
}
这是执行结果
Thread[lala,5,main],5
test的值增加为15
Thread[lala,5,main],15
Thread[mimi,5,main],15
test的值增加为25
Thread[mimi,5,main],25
Thread[popo,5,main],25
test的值增加为35
Thread[popo,5,main],35
大概就是这样子~
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.122.184.102
1F:推 qrtt1:没有同步的设计, 这真的是你要的吗? 02/21 14:03
2F:→ yangpika:你是说testAdd跟getTest需要多加synchronized吗?? 02/21 14:07
3F:→ yangpika:我会注意的 02/21 14:09
4F:推 H45:我得提示 singleton 和 reference 同一物件是两回事... 02/21 17:39
5F:→ yangpika:嗯嗯~感谢H45 我想这样也可以达到我的目的 02/21 17:51
6F:推 H45:很高兴你的问题解决了,但是我想和其他读者说 singleton 并非 02/21 18:02
7F:推 H45:解决此问题的最佳选项 :) 02/21 18:03
8F:推 zeat:我只有注意到没有同步...这样共用值就失去意义了吧@@ 02/21 21:12