作者jehovah (Lucius)
看板java
標題[問題] synchronized 和 multi thread
時間Tue Oct 4 22:57:39 2011
大家好, 小弟對multi thread還不熟悉, 想請教一個問題
目前我有A, B兩條thread, 以及一個公用的arraylist
A thread會做以下的工作:
arraylist.remove(old_index);
...一些運算
arraylist.add(new_index, obj);
B thread則會對arraylist作get
因此A在作add前, B有機會IndexOutOfBounds
我查了synchronized修飾字,
將A的工作用synchronized包起來, 可是沒有幫助
synchronized(arraylist){
...
}
我是希望鎖住arraylist這個物件, 而不是操作這物件的Method
請問一般來說, 這種狀況如何處理較恰當?
可否給我點建議, 或是該往哪個方向去查..謝謝:)
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 1.169.177.29
1F:推 tomap41017:thread b call arraylist.wait() 10/04 23:02
2F:→ tomap41017:在A thread做完之後去call arraylist.notifyAll() 10/04 23:04
3F:→ dou0228:未看先猜 ArrayList 不是 Collections.synchronizedList() 10/05 00:41
4F:→ dou0228:List l=Collections.synchronizedList(new ArrayList()); 10/05 00:44
5F:→ dou0228:... synchronized(list) { ... } 10/05 00:46
6F:→ jehovah:謝謝^^ 那請問用vector來做是否也可行? 10/05 00:48
7F:→ dou0228:可,因為 Collections.synchronizedList 傳入 List<T> list 10/05 00:51
8F:→ jehovah:抱歉再請教, 若為ArrayList<ArrayList<String>> 10/05 10:20
9F:→ jehovah:則Collections.synchronizedList會確保兩層同步嗎? 10/05 10:22
10F:→ jehovah:我測試了一下, 結果是內外獨立的 10/05 10:54
11F:→ dou0228:內外獨立正常,兩層都要 用 Collections. 來建才會 sync. 10/05 10:55
12F:推 dream1124:你可以用concurrent package 裡面寫好的資料結構 10/05 11:00
13F:→ jej:要先確定起的這個物件是不是唯一的.. 不是唯一的就鎖不起來 10/06 20:54