1, multi-threaded Way Exception Example 1.1, Java code as follows:
Finallist<string> myList = Createtestdata ();NewThread (NewRunnable () {@Override Public void Run() { for(String string:mylist) {System.out.println ("Traverse Collection value ="+ string);Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {E.printstacktrace (); }}}). Start ();NewThread (NewRunnable () {@Override Public void Run() { for(Iterator<string> it = Mylist.iterator (); It.hasnext ();) {String value = It.next (); System.out.println ("Delete element value ="+ value);if(Value.equals ("3")) {it.remove (); }Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {E.printstacktrace (); }}}). Start ();
1.2, the exception information printed as follows:
遍历集合 value = 1删除元素 value = 1删除元素 value = 2遍历集合 value = 2遍历集合 value = 3删除元素 value = 3删除元素 value = 4Exception in thread "Thread-0" java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372) at java.util.AbstractList$Itr.next(AbstractList.java:343) at com.primeton.test.Test$1.run(Test.java:119) at java.lang.Thread.run(Thread.java:619)删除元素 value = 5
This exception is thrown when the method detects concurrent modifications to an object, but does not allow this modification. This means that the above method is not a problem when executing on the same thread, but it is still possible to have an exception in asynchronous situations.
2. Workaround 2.1, use the following code, will not appear before the exception
FinalList<string> myList =NewCopyonwritearraylist<string> (); Mylist.add ("1"); Mylist.add ("2"); Mylist.add ("3"); Mylist.add ("4"); Mylist.add ("5");NewThread (NewRunnable () {@Override Public void Run() { for(String string:mylist) {System.out.println ("Traverse Collection value ="+ string);Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {E.printstacktrace (); }}}). Start ();NewThread (NewRunnable () {@Override Public void Run() { for(inti =0; I < mylist.size (); i++) {String value = Mylist.get (i); System.out.println ("Delete element value ="+ value);if(Value.equals ("3") {Mylist.remove (value); i--;//Note}Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {E.printstacktrace (); }}}). Start ();
2.2. Output results
遍历集合 value = 1删除元素 value = 1遍历集合 value = 2删除元素 value = 2遍历集合 value = 3删除元素 value = 3遍历集合 value = 4删除元素 value = 4遍历集合 value = 5删除元素 value = 5
3. Related summary
1. Use the Collections.synchornizedxxx method to obtain a thread-safe object
2, using Java.util.concurrent/java.util.concurrent.atomic concurrent programming object development
Additional Java thread-safe classes: HashTable, vectors, stacks, stringbuffer, etc.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Concurrentmodificationexception Exception Summary-multithreading mode