public class GameLoopThread extends Thread
   {
    static final long FPS = 10;
    private GameView view;
    private boolean running = false;
    public GameLoopThread(GameView view)
     {
         this.view = view;
     }
   public void setRunning(boolean run)
   {
         running = run;
   }
   @Override
   public void run()
   {
         long ticksPS = 1000 / FPS;
         long startTime;
         long sleepTime;
         while (running)
         {
                Canvas c = null;
                startTime = System.currentTimeMillis();
                try
                {
                       c = view.getHolder().lockCanvas();
                       synchronized (view.getHolder())
                       {
                              view.onDraw(c);
                       }
                }
                finally
                {
                       if (c != null)
                       {
                              view.getHolder().unlockCanvasAndPost(c);
                       }
                }
                sleepTime = ticksPS-(System.currentTimeMillis() - startTime);
                try
                {
                       if (sleepTime > 0)
                              sleep(sleepTime);
                       else
                              sleep(10);
                }
                 catch (Exception e){

               }
            }
       }
  }


我的困惑是
  我有初始化->私人布尔运行=假;
   之后,我分配->

public void setRunning(boolean run)
   {
         running = run;
   }


那么“运行”的真正含义是什么,“运行”的价值是什么呢?sombody plz解释setRunning(boolean run)方法。

最佳答案

run将保留您作为setRunning()方法的参数传递的所有内容。它是truefalse

从代码的外观来看,它似乎可以控制重新绘制Canvas。只要runningtrue(通过在setRunning(true)上调用Thread),它将每100毫秒(或每秒10帧)重新绘制Canvas

编辑

您应该使用running修饰符声明volatile,以便进行正确的同步。如果不包括修饰符,而从另一个线程调用setRunning(),则不能保证“预期”结果。

请参见here

10-07 13:14