gpt4 book ai didi

Java-同步列表

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:56:35 25 4
gpt4 key购买 nike

我已经在这个问题上停留了一段时间,所以非常感谢任何帮助。

我有以下代码部分:

BallThread.java
@Override
public synchronized void run() {
while (numItersCompleted < maxNumIters) {
completedThisIter = false;
synchronized (ballList) {
for (Ball b : ballList) { // line 35
b.updatePosition(ballPanel.getBounds(), ballList);
}
}
} // other stuff


Exception in thread "Thread-2" java.util.ConcurrentModificationException
at java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1091)
at java.util.ArrayList$SubList.listIterator(ArrayList.java:972)
at java.util.AbstractList.listIterator(AbstractList.java:300)
at java.util.ArrayList$SubList.iterator(ArrayList.java:968)
at Part2.BallThread.run(BallThread.java:35)

有时我会得到这个(BallPanel 中的第 36 行)

java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:782)
at java.util.ArrayList$Itr.next(ArrayList.java:754)
at Part2.BallPanel.paintComponent(BallPanel.java:36)
at javax.swing.JComponent.paint(JComponent.java:1029)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5138)
at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:302)
at javax.swing.RepaintManager.paint(RepaintManager.java:1188)
at javax.swing.JComponent._paintImmediately(JComponent.java:5086)
at javax.swing.JComponent.paintImmediately(JComponent.java:4896)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:783)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:735)

最佳答案

在看不到其余代码的情况下,一种解决方法是将 ballList 声明如下:

private final List<Ball> ballList = Collections.synchronizedList(...);

synchronizedList 的所有操作尝试在每个方法之前同步自身,这将使您的迭代完全安全,只要您保持当前的 synchronized(ballList) 就位。

关于Java-同步列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11623428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com