起初,我对这个话题有点困惑,因为我找到的大多数例子都没有上下文。我终于找到了这篇为我解决问题的博客文章: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();
}
}