情況1:這不會導致ConcurrentModificationException
?誰能告訴我爲什麼這不會導致ConcurrentModificationException。任何人都可以通過ConcurrentModificationException解釋我嗎?
public class UpdatePeople {
List <People> records = new ArrayList <People>();
public class AsyncTask extends AsyncTask < Void, Void, Boolean > {
List <People> people;
public AsyncTask(List <People> allergy) {
this.people = people;
}@
Override
protected Boolean doInBackground(Void...params) {
List <String> responses = new ArrayList <String>();
for (People peopleList: this.people) {
}
}
}
}
案例2:這會導致ConcurrentModificationException
因爲我試圖訪問的人在我AsyncThread這不是線程安全的列表。我可以讓我的人員列表實現CopyOnWriteArrayList
這是線程安全的,這應該工作。
public class UpdatePeople {
List <People> records = new ArrayList <People>();
public class AsyncTask extends AsyncTask < Void, Void, Boolean > {
@
Override
protected Boolean doInBackground(Void...params) {
List <String> responses = new ArrayList <String>();
for (People peopleList: records) {
}
}
}
}
- 任何人都可以解釋我什麼是
case 1
恰好發生。我無法理解這是如何解決ConcurrentModificationException
問題的。 - 是否將案例2從
ArrayList
更改爲CopyOnWriteArrayList
推薦?
添加異常:
05-28 20:34:21.073:E/XXX(904):未捕獲的例外情況是:05-28 20:34:21.073:E/XXX(904):了java.lang.RuntimeException:一個錯誤而執行doInBackground發生 ()05-28 20:34:21.073:E/XXX(904):在 android.os.AsyncTask $ 3.done(AsyncTask.java :299)05-28 20:34:21.073: E/XXX(904):at java.util.concurrent.FutureTask $ Sync.innerSetException(FutureTask.java:273) 05-28 20:34:2 1.073:E/XXX(904):at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 05-28 20:34:21.073:E/XXX(904):at java.util。 concurrent.FutureTask $ Sync.innerRun(FutureTask.java:307) 05-28 20:34:21.073:E/XXX(904):在 java.util.concurrent.FutureTask.run(FutureTask.java:137)05 -28 20:34:21.073:E/XXX(904):在 android.os.AsyncTask $ $ SerialExecutor 1.run(AsyncTask.java:230)05-28 20:34:21.073:E/XXX(904 ): java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 05-28 20:34:21.073:E/XXX(904):at java.util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor.java:569) 05-28 20:34:21.073:E/XXX(904):在 java.lang.Thread.run(Thread.java:856)05-28 20:34:21.073:E/XXX(904): 引起:JAVA .util.ConcurrentModificationException 05-28 20:34:21.073:E/XXX(904):在 的java.util.ArrayList $ ArrayListIterator.next(ArrayList.java:569)
請加異常的消息,那就是「爲(人民peopleList:記錄)」中的代碼迴路你的問題 – mschenk74
@ mschenk74:在我收到第二種情況下,exeception是環路for(People peopleList:records) – theJava
當你有一個迭代器的時候,你已經掌握了修改對象的權利。 –