Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中带同步的迭代器和迭代器列表_Java - Fatal编程技术网

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

java中带同步的迭代器和迭代器列表,java,Java,我有一个arraylist,我想同时(几乎)添加和删除许多项。所以我决定创建两个方法。在第一种方法中,我实现了包含remove部分的方法,我使用了如下内容: //my list ArrayList<Human> list= new ArrayList<Human>(100); //Human is the object of the class Human List<Human> syncList = Collections.sync

我有一个arraylist,我想同时(几乎)添加和删除许多项。所以我决定创建两个方法。在第一种方法中,我实现了包含remove部分的方法,我使用了如下内容:

   //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);
//我的列表
ArrayList=新的ArrayList(100);
//人是类人的客体
List syncList=Collections.synchronizedList(新的ArrayList());
已同步(同步列表){
for(迭代器iter=list.Iterator();iter.hasNext();){
Human=iter.next();
-
-
//使用迭代器的removes方法
移除(某物);
在第二种方法中(我需要添加很多项),类似这样:

            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)
for(ListIterator it=list.ListIterator();it.hasNext();){
List syncList=Collections.synchronizedList(newArrayList());
已同步(同步列表){
-
- 
//使用迭代器列表的add方法
添加(某物)

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

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

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

直接添加和删除从列表中?这两个方法使用它们自己的本地列表。它们不共享同一个列表。列表是全局的。我只是在那里添加了,以便查看和实际使用的列表。对于混淆,抱歉,直接从列表中添加和删除添加和删除直接从列表中删除?这两个方法使用它们自己的本地列表。它们不共享同一个列表。the列表是全局的。我只是在那里添加,以便查看我实际使用的列表。对于混淆,请直接从列表中添加和删除