您能否告诉我在单线程环境中是否可能发生并发修改异常以及我发布的以下应用程序由两个线程组成,请告诉我我能否在单个线程中也看到相同的异常......请建议
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();
}
请告知有什么方法可以克服它..这样就不会出现此错误..!!请告知