[問題] synchronized 和 multi thread

看板java作者 (Lucius)時間14年前 (2011/10/04 22:57), 編輯推噓2(2012)
留言14則, 5人參與, 最新討論串1/3 (看更多)
大家好, 小弟對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

10/04 23:02, , 1F
thread b call arraylist.wait()
10/04 23:02, 1F

10/04 23:04, , 2F
在A thread做完之後去call arraylist.notifyAll()
10/04 23:04, 2F

10/05 00:41, , 3F
未看先猜 ArrayList 不是 Collections.synchronizedList()
10/05 00:41, 3F

10/05 00:44, , 4F
List l=Collections.synchronizedList(new ArrayList());
10/05 00:44, 4F

10/05 00:46, , 5F
... synchronized(list) { ... }
10/05 00:46, 5F

10/05 00:48, , 6F
謝謝^^ 那請問用vector來做是否也可行?
10/05 00:48, 6F

10/05 00:51, , 7F
可,因為 Collections.synchronizedList 傳入 List<T> list
10/05 00:51, 7F

10/05 10:20, , 8F
抱歉再請教, 若為ArrayList<ArrayList<String>>
10/05 10:20, 8F

10/05 10:22, , 9F
則Collections.synchronizedList會確保兩層同步嗎?
10/05 10:22, 9F

10/05 10:54, , 10F
我測試了一下, 結果是內外獨立的
10/05 10:54, 10F

10/05 10:55, , 11F
內外獨立正常,兩層都要 用 Collections. 來建才會 sync.
10/05 10:55, 11F

10/05 11:00, , 12F
你可以用concurrent package 裡面寫好的資料結構
10/05 11:00, 12F

10/06 20:54, , 13F
要先確定起的這個物件是不是唯一的.. 不是唯一的就鎖不起來
10/06 20:54, 13F
文章代碼(AID): #1EYnxcms (java)
文章代碼(AID): #1EYnxcms (java)