看板 java 關於我們 聯絡資訊
大家好, 小弟對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
tomap41017:thread b call arraylist.wait() 10/04 23:02
tomap41017:在A thread做完之後去call arraylist.notifyAll() 10/04 23:04
dou0228:未看先猜 ArrayList 不是 Collections.synchronizedList() 10/05 00:41
dou0228:List l=Collections.synchronizedList(new ArrayList()); 10/05 00:44
dou0228:... synchronized(list) { ... } 10/05 00:46
jehovah:謝謝^^ 那請問用vector來做是否也可行? 10/05 00:48
dou0228:可,因為 Collections.synchronizedList 傳入 List<T> list 10/05 00:51
jehovah:抱歉再請教, 若為ArrayList<ArrayList<String>> 10/05 10:20
jehovah:則Collections.synchronizedList會確保兩層同步嗎? 10/05 10:22
jehovah:我測試了一下, 結果是內外獨立的 10/05 10:54
dou0228:內外獨立正常,兩層都要 用 Collections. 來建才會 sync. 10/05 10:55
dream1124:你可以用concurrent package 裡面寫好的資料結構 10/05 11:00
jej:要先確定起的這個物件是不是唯一的.. 不是唯一的就鎖不起來 10/06 20:54