所以我有一個由多個線程訪問下面的列表:我需要同步兩種方法和對象
ArrayList<String> listOfString = Collections.synchronizedList(new ArrayList<String>());
我知道,當我遍歷列表我要像這樣同步:
synchronized(listOfString)
{
for(String s : listOfString) System.out.println(s);
listOfString.clear();
}
,如果我要刪除的東西,難道我這樣做什麼:
public void removeString(String s)
{
listOfString.remove(s);
}
或本:
public synchronized void removeString(String s)
{
listOfString.remove(s);
}
個人而言,如果我要去可以通過'List'迭代的地方......我不與'Collections.synchronizedList打擾()'調用,只需在'List'同步的*所有*操作。這是旁邊的人誰讀/觸摸代碼更加明確。 –