您能否告诉我,是否有任何方法可以在单线程环境中发生并发修改异常,我发布的以下应用程序也由两个线程组成,请告诉我我是否可以在单线程中看到相同的异常..请建议
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)