如何实现paint-update循环?

时间:2010-09-08 15:43:54

标签: android

我想在Android上为画布上的游戏动画创建一个绘画和更新循环但是我遇到了麻烦,因为我似乎无法让线程正常工作。它似乎几乎立即崩溃。这是我尝试过的:

    // Create the thread supplying it with the runnable object
    Thread thread = new Thread(runnable);

    // Start the thread in oncreate()
    thread.start();


    class runner implements Runnable {
    // This method is called when the thread runs
    long wait = 1000;

    public void run() {

    update();
    }

    public void update()
    {
        try{
          Thread.currentThread();
            //do what you want to do before sleeping
          Thread.sleep(wait);//sleep for 1000 ms
          //do what you want to do after sleeping
        }
        catch(InterruptedException ie){
        //If this thread was interrupted by another thread 
        }

        run();
    }
}

当我将等待降低时,它会更快地崩溃。

有没有更合适的方法来解决这个问题?

改为:

class runner implements Runnable {
// This method is called when the thread runs
long wait = 10;
boolean blocked = false;

public void run() {

    if(!blocked){
        blocked = true;
        paint();
    }
}


public void paint()
{

    update();
}


public void update()
{
    try{
      Thread.currentThread();
        //do what you want to do before sleeping
      Thread.sleep(wait);//sleep for 1000 ms
      //do what you want to do after sleeping
    }
    catch(InterruptedException ie){
    //If this thread was interrupted by another thread 
    }

    paint();
}

}

这会导致相同的错误......:/

2 个答案:

答案 0 :(得分:4)

我注意到的第一件事是运行调用更新和更新调用运行。这将导致无意外堆栈溢出。他们互相打电话直到筹码堆满为止。然后它应该崩溃。

答案 1 :(得分:1)

你错过了'循环'。

您不应该在已启动的线程上手动调用run。

public void run()
{
  while (true)
  {
    // do whatever
    Thread.sleep(wait);
  }
}

我实际上也不会使用上面的,我会使用Timer或Android等价物。你应该从中得到这个概念。