Re: [問題] 兩個thread要reference到同一個object
感謝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
推
02/21 14:03, , 1F
02/21 14:03, 1F
→
02/21 14:07, , 2F
02/21 14:07, 2F
→
02/21 14:09, , 3F
02/21 14:09, 3F
推
02/21 17:39, , 4F
02/21 17:39, 4F
→
02/21 17:51, , 5F
02/21 17:51, 5F
推
02/21 18:02, , 6F
02/21 18:02, 6F
推
02/21 18:03, , 7F
02/21 18:03, 7F
推
02/21 21:12, , 8F
02/21 21:12, 8F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 3 之 4 篇):