23

我想念 Android 中同步代码的概念。

设想

屏幕上始终绘制 3 个项目。每个图像都存储在一个 ArrayList (lstGraphics) 中。为此,我使用了 SurfaceView。一旦用户点击图像,图像的市场就会被移除,并且会添加一个新的市场。

代码示例:

动画隐藏线程

...
    @Override
        public void run() {
            Canvas c;
            while (run) {
                c = null;
                try {
                    c = panel.getHolder().lockCanvas(null);
                      synchronized (panel.getHolder()) {

                        panel.updatePhysics();
                        panel.manageAnimations();
                        panel.onDraw(c);

                    }
                } finally {
                    if (c != null) {
                        panel.getHolder().unlockCanvasAndPost(c);
                    }
                }
            }
        }    
...

因此,正如您首先看到的那样,我 updatePhysics()。这意味着我计算每个图像将移动到的方向。在这里,我还将从列表中删除点击的图像。之后,我检查是否需要在 manageAnimations() 的列表中添加一个新项目,然后最后一步绘制整个事物。

public class Panel extends SurfaceView implements SurfaceHolder.Callback {
....
 public void manageAnimations()
    {
          synchronized (this.getHolder()) {
            ...
        while (lstGraphics.size()<3) {
                lstGraphics.add(createRandomGraphic());
                }
        }
          }
    }

 @Override
    public boolean onTouchEvent(MotionEvent event) {
         synchronized (getHolder()) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                 //... check if a image has been clicked and then set its property
                        graphic.setTouched(true);

                 }
            }

            return true;
         }
    }

 public void updatePhysics() {
       synchronized (getHolder()) {

     for (Graphic graphic : lstGraphics) {
           //.... Do some checks
     if (graphic.isTouched())
      {
        lstGraphics.remove(graphic);
      }
     }
  }
 }

 @Override
    public void onDraw(Canvas canvas) {
         /// draw the backgrounds and each element from lstGraphics
}

public class Graphic {

        private Bitmap bitmap;
            private boolean touched;
            private Coordinates initialCoordinates; 
....
}

我得到的错误是:

> 03-01 10:01:53.365: ERROR/AndroidRuntime(454): Uncaught handler: thread Thread-12 exiting due to uncaught exception 
> 03-01 10:01:53.365: ERROR/AndroidRuntime(454): java.util.ConcurrentModificationException
> 03-01 10:01:53.365: ERROR/AndroidRuntime(454): at java.util.AbstractList$SimpleListIterator.next(AbstractList.java:66)
> 03-01 10:01:53.365: ERROR/AndroidRuntime(454): at com.test.customcontrols.Panel.updatePhysics(Panel.java:290)
> 03-01 10:01:53.365: ERROR/AndroidRuntime(454): at com.test.customcontrols.AnimationHideThread.run(AnimationHideThread.java:41)

任何帮助是极大的赞赏。谢谢你。

4

4 回答 4

78

您的问题在于您的物理方法,您可以在其中添加图形和列表

public void updatePhysics() {
    synchronized (getHolder()) {
        for (Graphic graphic : lstGraphics) {
        //.... Do some checks
        if (graphic.isTouched()) {
            lstGraphics.remove(graphic); //your problem
        }
    }
}

for(Graphic graphic : lstGraphics)和的组合lst.Graphics.remove(graphic);会导致 ConcurrentModificationException ,因为您在列表中运行并同时尝试修改它。

到目前为止,我知道两种解决方案:

  1. 如果有可用的迭代器,请改用迭代器(迄今为止从未为 Android 编码)。

    while (iter.hasNext) {
        if (physicsCondition) iter.remove();
    }
    
  2. 使用第二个列表来存储要删除的元素,然后再删除它们

    List<GraphicsItem> toRemove = new ....
    for (Graphic graphic : lstGraphics) {
        if (physicsCondition) {
            toRemove.add(graphic);
        }
    }
    lstGraphics.removeAll(toRemove);
    
于 2011-03-01T08:33:06.027 回答
9

正如@idefix 所说,您可以像这样在单线程上下文中轻松获取 ConcurrentModificationException :

public static void main(String[] args) {
    List<String> list = new ArrayList<String>(Arrays.asList("AAA", "BBB"));
    for (String s : list) {
        if ("BBB".equals(s)) {
            list.remove(s);
        }
    }
}
于 2011-03-01T08:59:08.147 回答
4

您可以使用 CopyOnWriteArrayList,如下所示:

    List<String> myList = new CopyOnWriteArrayList<String>();

    myList.add("1");
    myList.add("2");
    myList.add("3");
    myList.add("4");
    myList.add("5");

    Iterator<String> it = myList.iterator();
    while(it.hasNext()){
        String value = it.next();
        System.out.println("List Value:"+value);
        if(value.equals("3")){
            myList.remove("4");
            myList.add("6");
            myList.add("7");
        }
    }
于 2015-06-28T17:09:26.493 回答
1

这是我使用@idefix 第二种解决方案的方法:

private List<TYPE> getFilteredData(List<TYPE> data){                
    List<TYPE> toRemove = new ArrayList<TYPE>(data.size());     
    synchronized(data){
        for(TYPE f : data){
            if([CONDITION]){                        
                toRemove.add(f);
                Log.w(TAG, "Element removed: "+ f);                 
            }
        }
    }                   
    data.removeAll(toRemove);
    return data;        
}

谢谢@idefix +1

于 2014-05-09T00:00:17.157 回答