SurfaceView和Game线程同步

时间:2017-02-23 00:45:47

标签: android multithreading surfaceview

我有一个SurfaceView和一个GameThread,可以更新游戏状态并在画布上绘制位图。下面的surface.update()更新锁外的游戏变量,并创建一个必须在画布上绘制的位图。锁定surface.doDraw后,在画布上绘制该位图。 Update()是外部UI线程锁定是为了提高性能。这种方法有误吗?我是否必须在锁定下更新?

public class GameThread extends Thread {

private SurfaceHolder surfaceHolder;
private GameViewSurface surface;
private boolean running = false;

public GameThread(SurfaceHolder holder, GameViewSurface GameSurface) {
    surfaceHolder = holder;
    surface = GameSurface;
}

public void setRunning(boolean run) {
    running = run;
}

public boolean getRunning() {
    return running;
}

@Override
public void run() {
    while (running) {

        Canvas canvas=null;
        try {

            if(!surfaceHolder.getSurface().isValid())
                continue;

            surface.update();
            canvas = surfaceHolder.lockCanvas(null);
            synchronized (surfaceHolder) {

                surface.doDraw(canvas);
            }
        } catch(Exception p){


        }finally {
            if (canvas != null) {
                try {
                    surfaceHolder.unlockCanvasAndPost(canvas);
                }catch (Exception e){}
            }
        }
    }
}

}

0 个答案:

没有答案