Android 如何使用SurfaceView停止游戏

Android 如何使用SurfaceView停止游戏,android,multithreading,Android,Multithreading,当使用Surface View制作游戏时,我遇到了一个问题。我有一个MainThread类,所有更新函数都在run函数中。条件是: while(running){ //do anything } 我想停止玩游戏,并通过2个菜单项恢复游戏。在停止项中我设置了thread.setRunningfalse,在恢复项中我设置了thread.setRunningtrue,但它仍然保持运行 之后,我尝试在循环中放入一个布尔值,如下所示: while(running){ if(isPlayi

当使用Surface View制作游戏时,我遇到了一个问题。我有一个MainThread类,所有更新函数都在run函数中。条件是:

while(running){
    //do anything
}
我想停止玩游戏,并通过2个菜单项恢复游戏。在停止项中我设置了thread.setRunningfalse,在恢复项中我设置了thread.setRunningtrue,但它仍然保持运行

之后,我尝试在循环中放入一个布尔值,如下所示:

while(running){
    if(isPlaying == true){
        //do anything
    }
}
如果我想停止,我将布尔变量设置为false和true以继续。但这也不行。我需要做什么?

试试这个:

while(running){
    if(isPlaying == true){
        //do anything
    } else break;
}

如果设置为false,则线程将结束,并且不再停止,除非创建新线程。因此,您需要添加一个新的菜单项来控制退出。运行用于控制恢复和暂停。例如:

public class MainThread extends Thread{
    volatile boolean isQuit = false;
    volatile boolean running = false;
    Object lock = new Object();

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

    public void setQuit(boolean isQuit) {
        this.isQuit = isQuit;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();

        while (!isQuit) {
            if (!running) {
                System.out.println("pause ganme");
                synchronized (lock) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        System.out.println(e);
                        break;
                    }
                }
            }
            else {
                // continue game
                System.out.println("running ganme");
            }
        }

        System.out.println("quit ganme");
    }

    public void quit() {
        isQuit = true;
        running = false;
        synchronized (lock) {
            lock.notify();
        }
    }
}