简体   繁体   English

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

[英]Pausing and Resuming android thread in stateView class

I'm currently implementing an android game and faced a problem in pausing and resuming the thread. 我目前正在实现一个Android游戏,在暂停和恢复线程时遇到问题。 Here is the `package com.andromeda.bubbleshooter; 这是com.andromeda.bubbleshooter软件包;

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

public class MainThread extends Thread { 公共类MainThread扩展了Thread {

// 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

    }
}

} ` }`

In the Game loop class which extends surfaceView, I'm initializing the thread in the constructor, when clicking on the pause button I invoke .setRunning(false), and when resuming I invoke .setRunning(true). 在扩展surfaceView的Game循环类中,我正在初始化构造函数中的线程,当单击暂停按钮时,我调用.setRunning(false),而在恢复时我调用.setRunning(true)。 When pausing the game its ok, but when clicking back the button to resume, nothing changes and game is freezed. 暂停游戏可以,但单击返回按钮即可恢复正常,游戏不会冻结。

This is because when you set isRunning to false in pause, you exit the while loop and leave the run function, which causes the thread to end. 这是因为当您在暂停中将isRunning设置为false时,您退出了while循环并离开了run函数,这导致线程结束。 Rather than setting isRunning, you should provide some other form of synchronization. 而不是设置isRunning,您应该提供其他形式的同步。 One wasy way would be to have a semaphore with a single ticket. 一种浪费的方法是使用一张票来获得信号灯。 You could take it in pause() and release it in resume(), and take it then release it at the beginning of each run through the main thread loop. 您可以在pause()中使用它,然后在resume()中释放它,然后在每次主线程循环运行开始时将其释放。 That way if you're paused you'll wait for the semaphore to be released before running again. 这样,如果您暂停了,您将等待信号量释放后再运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM