1

Pongゲームの作成方法を示すガイドに従っています。スレッドを作成し、ボールを動かす関数を呼び出す部分があります。

これは私が作成したコードです:

package com.ozadari.pingpong;

public class PingPongGame extends Thread {
private Ball gameBall;
private PingPongView gameView;

public PingPongGame(Ball theBall,PingPongView mainView)
{
    this.gameBall = theBall;
    this.gameView = mainView;
}

@Override
public void run()
{
    while(true)
    {
        this.gameBall.moveBall();
        this.gameView.postInvalidate();

        try
        {
            PingPongGame.sleep(5);

        }
        catch(InterruptedException e)
        {

            e.printStackTrace();
        }

    }
}}

スレッドは呼び出されて機能していますが、何も出力されません。無限ループをキャンセルして、ループを100回実行しようとしました。しばらく待つと、100回実行した後のように画面に印刷されますが、途中で何も印刷されません。

何が問題ですか?どうすれば修正できますか?

4

1 に答える 1

2

投稿したコードからはわかりませんが、とにかく、ハンドラーを使用して、次のように1秒に1回実行することができます(時間を希望どおりに変更します)。

Handler handler = new Handler();
final Runnable r = new Runnable()
{
    public void run() 
        {
             //do your stuff here
              handler.postDelayed(this, 1000);
        }
};

handler.postDelayed(r, 1000);

http://developer.android.com/reference/android/os/Handler.html

通常のスレッドを使用して、最後にstartを呼び出すこともできます。

Thread thread = new Thread()
{
    @Override
    public void run() {
        try {
            while(true) {
                sleep(1000);
                handler.post(r);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};

thread.start();
于 2013-03-21T12:39:03.933 に答える