1


我正在为 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),那么接下来的三个形状将被自动丢弃(这不是什么我想)。

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

谢谢 :-)

4

1 回答 1

0

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

您无法同步整个 run() 方法,因为 run() 来自父(线程)类,而父类在声明中没有使用 synchonized。

我不知道如何解决你的其他问题,因为我现在不明白你的程序是如何工作的。

于 2011-04-10T00:30:15.997 回答