使用另一个线程

时间:2017-06-19 05:20:28

标签: android arrays multithreading android-canvas surfaceview

使用SurfaceView并从数组中绘制元素时遇到问题,该数组在另一个线程中更新。数组中的值始终不为null。下面我给出代码和错误消息。它可以连接什么?我很乐意帮忙!

SurfaceViewThread:

@Override
        public void run() {
            Canvas canvas;
            while (runFlag) {
                canvas = null;
                try {
                    // получаем объект Canvas и выполняем отрисовку
                    canvas = surfaceHolder.lockCanvas(null);
                    synchronized (bw.multithreadLayers) {
                        if (canvas == null) return;
                        p.setShader(new LinearGradient(0, 0, 0, scrH, bw.getColor(), bw.getColor2(), Shader.TileMode.MIRROR));
                        canvas.drawPaint(p);
                        p.setShader(null);
                        p.setTextSize(textSize);
                        p.setColor(0xFFffffff);

                        for (int i = 0; i<bw.multithreadLayers.size(); i++) {
                            try {
                                for (int j = 0; j<bw.multithreadLayers.get(i).size(); j++) {
                                    GObject go = bw.multithreadLayers.get(i).get(j);
                                    canvas.drawBitmap(go.getTexture(), go.getX(), scrH-go.getY()-go.getTexture().getHeight(), p);
                                }
                            } catch(Exception e) {
                                System.out.println("JException, " + i + ", " + e.getMessage());
                            }
                        }

                        canvas.drawBitmap(player, objX, objY, p);
//some code...
                    }
                } 
                finally {
                    if (canvas != null) {
                        surfaceHolder.unlockCanvasAndPost(canvas);
                    }
                }
            }
        }

MultithreadLayers:

lowLayers.clear();
        lowLayers.add(layer0);
        lowLayers.add(layer1);
        lowLayers.add(layer2Active);
        multithreadLayers = lowLayers;

例外:

06-19 08:05:41.967 I/System.out(30470): JException, 0, Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference

06-19 08:05:43.601 I/System.out(30470): JException, 1, Index: 1, Size: 3

1 个答案:

答案 0 :(得分:0)

我发现了问题。我忘了在ArrayList上调用clone():D

multithreadLayers = (ArrayList<ArrayList<GObject>>) lowLayers.clone();