正确使用wait()/ notify()进行俄罗斯方块游戏

时间:2011-04-09 23:59:52

标签: java android synchronization tetris


我正在为Android编写类似俄罗斯方块的游戏,我正在尝试实现“实时部分”。我有一些似乎有用的东西,但我想确保我的实现是正确的。

我想要的是:

  • 形状以固定的速率下降(假设我希望每次 y 形状减少时等待 n 毫秒)

  • 玩家可以随时删除形状,等待 n 毫秒的计时器必须立即中断并仅为下一个形状重新开始

  • 当形状下垂或形状不再下降时,游戏会在创建另一个形状之前等待 m 毫秒

  • 系统必须能够随时停止线程

我正在做的是以下内容(系统可以使用interrupt()停止线程):

class TetrisThread extends Thread {
    private int n = 3000; // for testing purposes, in the real game n will be smaller ;)
    private int m = 1000;

    @Override
    public void run() {
        doDraw();
        while(!interrupted())
        {
            try {
                synchronized (this) {
                    wait(n);
                }
                doPhysics();
                doDraw();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    // This method is the one which will drop the shape, it is called from another thread
    synchronized public boolean onTouch([…]) {
        […]
        // The shape has to be dropped
        dropShape();
        notify();
        […]
    }

    private void doPhysics() throws InterruptedException {
        […]
        // The shape cannot go down or has been dropped
        sleep(m);
        createNewShape();
        […]
    }
}

特别是,synchronized(this) { wait(n); }部分看起来很有趣,因为如果我理解正确,这将锁定this并立即释放。

但是wait()需要在synchronized(this)块中使用(为什么?)并且我无法同步整个run()方法,因为如果我尝试将其放置三倍的形状在sleep(m)调用期间,将自动删除三个下一个形状(这不是我想要的)。

这对你来说是否正确?
你有任何更正,建议或评论吗?

谢谢:-)

1 个答案:

答案 0 :(得分:0)

wait()方法用于使当前运行的线程等待调用wait()调用notify()的对象(在本例中为this)。 synchronized(this)部分需要确保当时只有一个帖子访问this

您无法同步整个run()方法,因为run()来自父(Thread)类,父进程未在声明中使用synchonized。

我不知道如何解决您的其他问题,因为我现在无法了解您的程序如何运作。

相关问题