2012-02-09 38 views
0

我有一个arraylist,我想添加和删除他在相同(几乎)时间很多项目。所以我决定创建2个方法。在第一种方法我实现它包含了我使用的东西,如删除部分的方法:这样迭代器和iteratorList在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方法完成时,另一个函数调用的列表没有适当的行为。我的意思是,一些元素没有添加或从列表中删除。我该如何解决这个问题?有什么想法?

+0

向我们展示您的*实际*代码。 – NPE 2012-02-09 18:35:52

+0

这两种方法使用他们自己的本地列表。他们不共享相同的列表。 – 2012-02-09 18:37:50

+0

该列表是全球性的。我只是在那里添加,以便查看和我实际使用的列表。对于混淆 – 2012-02-09 18:39:33

回答

3

您正在同步2个完全不同的对象,因此存在不一致的行为。您致电synchronizedList()正在返回一个包装围绕您正在同步的原始列表。由于2种方法使用不同的包装,因此不会发生实际的同步。你只需要在原始列表实现上同步。当然,任何其他使用名单成员应该被同步。