Java同步列表

我已经坚持了一段时间,因此非常感谢您的帮助.

我有以下代码部分:

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的所有操作都尝试在每种方法之前先进行自身同步,这将使您的迭代完全安全,只要您保持当前已同步(ballList)到位即可.

上一篇:进程同步 (Process Synchronization)


下一篇:varchar 存多少个汉字,多少个英文