【问题标题】:Pausing and Resuming android thread in stateView class在 stateView 类中暂停和恢复 android 线程
【发布时间】:2014-03-10 18:08:39
【问题描述】:

我目前正在实现一个 android 游戏,但在暂停和恢复线程时遇到了问题。 这是`package com.andromeda.bubbleshooter;

导入 android.graphics.Canvas; 导入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的游戏循环类中,我在构造函数中初始化线程,单击暂停按钮时调用.setRunning(false),恢复时调用.setRunning(true)。暂停游戏时没问题,但是当点击返回按钮恢复时,没有任何变化并且游戏被冻结。

【问题讨论】:

    标签: java android surfaceview


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      • 2016-03-24
      相关资源
      最近更新 更多