Thread to Runnable开关后Sprite不显示

时间:2015-02-01 06:43:56

标签: java android

我将一个线程从扩展的Thread切换到实现Runnable(实现Runnable是更好的做法,对吗?)所以当我调用surfaceCreated时我​​来自:

public void surfaceCreated(SurfaceHolder holder) {
    createSprites();
    gameLoopThread.setRunning(true);
    gameLoopThread.start();
}

为:

public void surfaceCreated(SurfaceHolder holder) {
    createSprites();
    gameLoopThread.setRunning(true);
    gameLoopThread.run();
}

因为start()方法未包含在Runnable接口中。但是,一旦我切换它,我的精灵就不再显示了。这是run()方法:

public void run() {
    Canvas c;
    while (running) {
        c = null;
        try {
            c = view.getHolder().lockCanvas();
            synchronized (mPauseLock) {
                view.onDraw(c);
            }
        } finally {
            if (c != null) {
                view.getHolder().unlockCanvasAndPost(c);
            }
        }

        synchronized (mPauseLock) {
            while (mPaused) {
                try {
                    mPauseLock.wait();
                } catch (InterruptedException e) {
                }
            }
        }

    }
}

在两个场景中都会调用它,但是只有在调用start()而不是直接调用run()时才会显示精灵。有人可以解释为什么会这样吗?

1 个答案:

答案 0 :(得分:2)

您无法通过致电Thread gameLoopThread.run()(或甚至致电Runnable获取run())来Thread开始Runnable。 您必须将Thread个实例传递给start()个实例,并为Thread调用public void surfaceCreated(SurfaceHolder holder) { createSprites(); gameLoopThread.setRunning(true); Thread t = new Thread(gameLoopThread); t.start(); }

例如:

{{1}}