一开始我对这个话题有点困惑,因为我发现的大多数例子都没有上下文。我终于找到了这篇博客文章,为我解决了问题:http: //netjs.blogspot.de/2015/09/how-and-why-to-synchronize-arraylist-in-java.html
从上面的示例看来,我只需要使用 Collections.synchronizeList() 转换我的列表,然后我就可以添加和删除项目而不必担心线程安全。但是在这里需要注意的是,在将列表传递给不同的线程之前,您必须同步列表,因为否则列表访问不是互斥的。
所以一个完整的例子是:
public class SynchroProblem implements Runnable{
private List<Integer> myList;
//Constructor
public SynchroProblem(List<Integer> myList){
this.myList = myList;
}
@Override
public void run() {
// Do stuff with the list .add(), .remove(), ...
myList.add(5);
// Even if mylist is synchronized the iterator is not,
// so for using the iterator we need the synchronized block
synchronized (myList){
// do stuff with iterator e.g.
Iterator<Integer> iterator = myList.iterator();
while (iterator.hasNext()){
int number = iterator.next();
if (number == 123){
iterator.remove();
}
}
}
}
public static void main(String[] args) {
List<Integer> originalList = new ArrayList<Integer>();
// Synchronize list
List<Integer> syncList = Collections.synchronizedList(originalList);
// Create threads and pass the synchronized list
Thread t1 = new Thread(new SynchroProblem(syncList));
Thread t2 = new Thread(new SynchroProblem(syncList));
t1.start();
t2.start();
}
}