作者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
推 qrtt1:沒有同步的設計, 這真的是你要的嗎? 02/21 14:03
→ yangpika:你是說testAdd跟getTest需要多加synchronized嗎?? 02/21 14:07
→ yangpika:我會注意的 02/21 14:09
推 H45:我得提示 singleton 和 reference 同一物件是兩回事... 02/21 17:39
→ yangpika:嗯嗯~感謝H45 我想這樣也可以達到我的目的 02/21 17:51
推 H45:很高興你的問題解決了,但是我想和其他讀者說 singleton 並非 02/21 18:02
推 H45:解決此問題的最佳選項 :) 02/21 18:03
推 zeat:我只有注意到沒有同步...這樣共用值就失去意義了吧@@ 02/21 21:12