您能否告诉我在单线程环境中是否有可能发生并发修改异常的方法,我下面发布的以下应用程序由两个线程组成,请告诉我我也可以在单个线程中看到相同的异常..请劝告
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(); }
请告知解决该问题的方法是什么..这样就不会出现此错误.. !!
ConcurrentModificationException可以在单线程环境中引发A。只要在不应该在上下文中修改对象的情况下使用它,就不必在另一个线程中进行修改。
ConcurrentModificationException
例:
public class CME { public static void main(String...args) { HashSet<Integer> coll = new HashSet<Integer>(); coll.add(1); coll.add(2); coll.add(3); for(Integer i : coll) { coll.remove(i); // Throws ConcurrentModificationException } } }