在java中同步的迭代器和迭代器列表



我有一个数组列表,我想同时(几乎)添加和删除许多项。所以我决定创建两个方法。在第一种方法中,我实现了包含删除部分的方法,我使用了类似的东西:

   //my list
   ArrayList<Human> list= new ArrayList<Human>(100);
   //Human is the object of the class Human
   List<Human> syncList = Collections.synchronizedList(new ArrayList<Human>());
   synchronized (syncList){
    for (Iterator<Human> iter = list.iterator(); iter.hasNext();) {
       Human = iter.next();
              -
              -
          //using the removes method of the iterator
          it.removes(something);

在第二种方法中(我需要添加许多项目),类似于这样的东西:

            for(  ListIterator<Human> it = list.listIterator();it.hasNext();){  
            List<Human> syncList = Collections.synchronizedList(newArrayList<Human>());
        synchronized (syncList){
                   -
                   - 
          //using the add method of the iterator list
          it.add(something)

现在我意识到,当这两个void方法完成时,另一个函数调用的列表没有适当的行为。我的意思是,有些元素没有添加或从列表中删除。我该怎么解决这个问题?有什么想法吗?

您在两个完全不同的对象上进行同步,因此行为不一致。您对synchronizedList()的调用将返回一个包装器,该包装器围绕您正在同步的原始列表。由于这两种方法使用不同的包装器,因此没有发生实际的同步。您只需要在原始列表实现上同步即可。当然,列表成员的任何其他使用也应该同步。

最新更新