在stateView类中暂停和恢复android线程

时间:2014-03-10 18:08:40

标签: java android surfaceview

我目前正在实施一款Android游戏,并在暂停和恢复线程方面遇到了问题。 这是`package com.andromeda.bubbleshooter;

import android.graphics.Canvas; import android.view.SurfaceHolder;

公共类MainThread扩展了线程{

// flag to hold game state
private boolean running;
public static boolean stop;

private SurfaceHolder surfaceHolder;
public GameLoop gamePanel;

public MainThread(SurfaceHolder surfaceHolder, GameLoop gamePanel) {
    super();
    this.surfaceHolder = surfaceHolder;
    this.gamePanel = gamePanel;
}

public void setRunning(boolean running) {
    this.running = running;
}

@Override
public void run() {
    Canvas canvas = null;
    while (running) {

        // update game state
        // render state to the screen
        try {
            canvas = this.surfaceHolder.lockCanvas();
            synchronized (surfaceHolder) {
                // if (running)
                gamePanel.draw(canvas);
            }
        } finally {
            // in case of an exception the surface is not left in
            // an inconsistent state
            if (canvas != null) {
                surfaceHolder.unlockCanvasAndPost(canvas);
            }
        } // end finally

    }
}

} `

在扩展surfaceView的Game循环类中,我正在构造函数中初始化线程,当单击暂停按钮时,我调用.setRunning(false),并在恢复时调用.setRunning(true)。暂停游戏时可以正常,但是当点击按钮恢复时,没有任何变化,游戏也会被冻结。

1 个答案:

答案 0 :(得分:0)

这是因为当你在暂停时将isRunning设置为false时,退出while循环并离开run函数,这会导致线程结束。您应该提供其他形式的同步,而不是设置isRunning。一种方法是拥有一张单票的信号量。你可以把它放在pause()中并在resume()中释放它,然后在每次运行开始时通过主线程循环释放它。这样,如果你暂停了,我会等待信号量在再次运行之前被释放。