gpt4 book ai didi

java - 关于并发修改异常

转载 作者:行者123 更新时间:2023-12-01 17:30:11 26 4
gpt4 key购买 nike

您能否告诉我,是否有任何方法可以在单线程环境中发生并发修改异常,我发布的以下应用程序也由两个线程组成,请告诉我我是否可以在单线程中看到相同的异常..请指教

package concurrentmodificationError;

import java.util.*;

class ItrDemo
{
public static void main(String arg[])
{
Vector v=new Vector();
v.addElement("Amit");
v.add("Rahul");
v.add(1,"Nitin");
v.addElement("Ankit");
System.out.println("There are "+v.size()+"elements in the vector ");

final Iterator itr=v.iterator();
Thread th=new Thread() {
public void run()
{
System.out.println("New Thread started,traversing elements of vector...");
System.out.println("Contents of vector are...");
while(itr.hasNext())
{
System.out.println(itr.next());
try
{
Thread.sleep(2000);
}
catch(Exception e1)
{
}
}
}
};// end of annomyous class
System.out.println("Suspending main thread and starting a new thread for traversing the contents of vector...");
th.start();
try
{
Thread.sleep(1000);
}
catch(Exception e1)
{
}
System.out.println("main thread resumed,modifying vector...");
v.remove("Ankit");
v.add("Puneet");
v.add("Raman");
System.out.println("Vector Modified , Ankit removed and Puneet & Raman added.");
}

}

是的,我知道在单线程环境中可能会出现此错误..如下面的代码所示..

System.out.println("Content of list are : ");
ListIterator itr1=list.listIterator();
while(itr1.hasNext())
{
list.add(new Emp("Anand","Manager",56000)); //
Emp e=(Emp)itr1.next();
e.display();
}

请告知有什么方法可以克服它..以免出现此错误..!!请告知

最佳答案

是的,在单线程环境中也可能出现此异常(不是错误)。更准确地说,只要当前正在迭代的集合被另一个线程或当前线程修改,就会引发异常。

出现此错误的单线程场景示例如下:

Iterator<String> names = namesList.iterator();
while(names.hasNext()){
String currentName = names.next();
if(currentName.startsWith("A")){
namesList.remove(currentName); //here you modify the original collection
}
}

在这种情况下,如果迭代器是一个快速失败迭代器(正如大多数集合实现提供的那样),您将得到一个 ConcurrentModificationException

关于java - 关于并发修改异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11828639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com