簡體   English   中英

為什么這段代碼會在Java中導致ConcurrentModificationException?

[英]Why does this code cause a ConcurrentModificationException in Java?

為什么這段代碼會在Java中導致ConcurrentModificationException?

public class MainMenuState {
    protected void init() {
        this.addElements(
             new GUIElement()
             .addMousePressed((e, element) -> {
                   this.elements.add(new GUIElement()
                   .addMouseEntered((e, element) -> //...)
             }
        )
   );
}

addElements定義為:

void addElements(GameElement... elements){
    this.elements.addAll(Arrays.asList(elements));
}

我希望代碼創建另一個GUIElement並在單擊封閉的GUIElement時將其添加到列表elements 而是在單擊它時,拋出ConcurrentModificationException 我理解在向元素添加元素時修改列表時拋出ConcurrentModificationException ,但是在elements被修改之后才調用mouseEntered

那么這個錯誤是怎么發生的?

錯誤文字:

Exception in thread "Thread-2" java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
at java.util.LinkedList$ListItr.next(Unknown Source)
at java.lang.Iterable.forEach(Unknown Source)
at code.state.GameState.render(GameState.java:34)
at code.state.Handler.render(Handler.java:32)
at code.state.Handler.render(Handler.java:28)
at code.frame.GameEngine.render(GameEngine.java:94)
at code.frame.GameEngine.run(GameEngine.java:68)
at java.lang.Thread.run(Unknown Source)

我認為這里沒有足夠的背景來准確找出問題的原因。 但一種解決方案就是使用:

 List<Object> objList = Collections.synchronizedList(new ArrayList<Object>());

實例化有問題的列表以簡單地同步對它的訪問。

我假設你在code.frame.GameEngine.render()方法中渲染了一些內容。 問題是你使用的是一個非線程安全的LinkedList 因此,當code.frame.GameEngine.render()方法迭代elements (這是異步發生)時,可以向elements添加新的GUIElement 您需要使用線程安全的集合,如:

List<GUIElement> elements = Collections.synchronizedList(new LinkedList<GUIElement>());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM