-1

我已經創建了這個簡單的工作線程,通過迭代ArrayList來計算迴文。 當我執行行temp_str1 = it.next();時,我得到一個錯誤。 ArrayList buffer_List沒有被任何其他線程使用,因此使用synchronized塊無助於此。我查看了以前的問題,但他們沒有太多幫助。我急於找到解決這個問題的辦法。iterator.next()中的ConcurrentModificationException多線程

這裏是我的代碼:

private void find_Palindromes(ArrayList<String> buffer_List){ 
    Iterator<String> it = buffer_List.iterator(); 
    String temp_str1, temp_str2; 
    while(it.hasNext()){ 
     temp_str1 = it.next(); 
     //System.out.println(temp_str1); 
     it.remove(); 

     if(is_Palindrome(temp_str1)){ 
      to_Shared_Queue(temp_str1); 
      palin_count++; 
     } 
    } 
} 

編輯代碼:加入to_Shared_Queue

private void to_Shared_Queue(String str){   
     synchronized(shared_queue){ 
      Shared_queue.add(str); 
     } 
    } 
+0

您的[mcve]請。 –

+0

看看這傢伙的回答,可能會幫助你。這是您用來從ArrayList中移除項目的移除方法。 http://stackoverflow.com/questions/15993356/how-iterators-remove-method-actually-remove-an-object – kevto

+2

我敢打賭,你正在修改to_Shared_Queue方法中的buffer_List。 – MGorgon

回答

-2

這是因爲你修改迭代循環的同時在它的。你可以通過從你的數組buffer_List中移除它來完成它。 buffer_List.remove(temp_str1);

+1

這看起來與我們推薦的完全相反。 –