并发修改异常,无法弄明白

时间:2014-01-28 22:43:36

标签: java android

似乎无论我做什么,我都得到了并发修改异常。我做了一些研究,根据我的理解,当您尝试编辑列表同时迭代它时,会发生此异常。但我仍然无法弄清楚究竟是什么导致它。所以我希望一些更有经验的人能帮助我弄清楚我在哪里出错了。这是我的代码。

package com.gametest;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;

public class GameSurfaceView extends Activity implements OnTouchListener {


    double ran;
    int touchX, touchY, screenWidth, screenHeight, objX, objY;
    static boolean canUpdate;
    static int enemyCount;
    static MyView v;
    static Bitmap orb, explosion;
    static List<Sprite> enemiesList = new ArrayList<Sprite>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        v = new MyView(this);
        v.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent me) {
                touchX = (int) me.getX();
                touchY = (int) me.getY();
                for (Sprite sprite : enemiesList) {
                    sprite.checkTouch(touchX, touchY);
                }

                return true;
            }
        });
        canUpdate = true;
        ran = 0;
        orb = BitmapFactory.decodeResource(getResources(), R.drawable.blue_orb);
        explosion = BitmapFactory.decodeResource(getResources(), R.drawable.explosion);
        createEnemies();
        setContentView(v);
    }

    private synchronized void createEnemies() {
        if (enemyCount < 5) {
            screenWidth = v.getWidth();
            screenHeight = v.getHeight();
            int listLength = enemiesList.size();
            enemiesList.add(new Sprite(v, orb, explosion, screenWidth, screenHeight, listLength));
            enemyCount = enemyCount + 1;
        }
    }

    public static synchronized void checkECount(int id) {
        canUpdate = false;
        enemyCount = enemyCount - 1;
        enemiesList.remove(id);
        int index = 0;
        Iterator<Sprite> itr = enemiesList.iterator();
          while(itr.hasNext()) {
              Sprite s = itr.next();
                s.ID = index;
                index++; 
          }
        canUpdate = true;

    }

    @Override
    protected void onPause() {
        super.onPause();
        v.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        v.resume();
    }

    public class MyView extends SurfaceView implements Runnable {

        Thread t = null;
        SurfaceHolder holder;
        boolean isItOk = false;

        public MyView(Context context) {
            super(context);
            holder = getHolder();

        }

        @Override
        public void run() {
            while (isItOk == true) {
                if (!holder.getSurface().isValid()) {
                    continue;
                }
                Canvas c = holder.lockCanvas();
                if(canUpdate){
                canvas_draw(c);
                }
                holder.unlockCanvasAndPost(c);

            }

        }

        protected synchronized void canvas_draw(Canvas canvas) {
            canvas.drawARGB(255, 50, 10, 10);
            String ranString = Integer.toString(screenHeight);
            ran = Math.random() * 5;
            if (ran > 3) {
                createEnemies();
            }

            Paint paint = new Paint();
            paint.setColor(Color.BLACK);
            paint.setTextSize(15);
            canvas.drawText(ranString, 10, screenHeight - 25, paint);
            for (Sprite sprite : enemiesList) {
                sprite.sprite_draw(canvas);
            }
        }

        public void pause() {
            isItOk = false;
            while (true) {
                try {
                    t.join();
                } catch (InterruptedException e) {

                }
                break;
            }
            t = null;
        }

        public void resume() {
            isItOk = true;
            t = new Thread(this);
            t.start();
        }

    }

    @Override
    public boolean onTouch(View arg0, MotionEvent arg1) {
        // TODO Auto-generated method stub
        return false;
    }

}

这是logCat

01-28 23:25:56.749: E/AndroidRuntime(5452): FATAL EXCEPTION: main
01-28 23:25:56.749: E/AndroidRuntime(5452): java.util.ConcurrentModificationException
01-28 23:25:56.749: E/AndroidRuntime(5452):     at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at com.gametest.GameSurfaceView$1.onTouch(GameSurfaceView.java:42)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.View.dispatchTouchEvent(View.java:7122)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1877)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1877)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1877)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1925)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1379)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.app.Activity.dispatchTouchEvent(Activity.java:2396)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1873)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.View.dispatchPointerEvent(View.java:7307)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3172)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3117)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4153)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4132)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4224)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:171)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.os.MessageQueue.nativePollOnce(Native Method)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.os.MessageQueue.next(MessageQueue.java:125)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.os.Looper.loop(Looper.java:124)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at android.app.ActivityThread.main(ActivityThread.java:4745)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at java.lang.reflect.Method.invokeNative(Native Method)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at java.lang.reflect.Method.invoke(Method.java:511)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-28 23:25:56.749: E/AndroidRuntime(5452):     at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:1)

问题是您可能正在修改“enemiesList”(例如删除/添加元素),而列表在此处显示:

for (Sprite s : enemiesList) {
        s.ID = index;
        index++;
}

尝试使该方法同步,看看会发生什么(以及将元素添加到列表中的那个):

public synchronized static void checkECount(int id) {
    canUpdate = false;
    enemyCount = enemyCount - 1;
    enemiesList.remove(id);
    int index = 0;
    for (Sprite s : enemiesList) {
        s.ID = index;
        index++;
    }
    canUpdate = true;

}

我实际上在调用“createEnemies”时看到了潜在的灾难,试试看看会发生什么......

希望这有助于......

问候!

答案 1 :(得分:0)

这看起来像你的问题:

for (Sprite s : enemiesList) {
        s.ID = index;
        index++;
    }

在迭代它时修改Sprite类中的变量会抛出异常。尝试声明方法同步如下:

protected synchronized void canvas_draw(Canvas canvas) {

或使用Iterator

答案 2 :(得分:0)

如果列表中的遍历操作数量远远超过了变异操作,则可能需要使用CopyOnWriteArrayList。它有一个快照式迭代器,允许您迭代列表,即使它在此期间被更改。但请注意,顾名思义,每当您对其进行更改时,它都会创建一个全新的基础数组副本。 IE,如果你做了太多的改变,它可能会影响性能。