理解setRunning(布尔运行)方法的问题

时间:2011-08-15 17:34:19

标签: java android methods

  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){ 

               }
            }
       }
  }

我的困惑是   我有初始化 - > private boolean running = false;    之后我分配了 - >

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

那么“正在运行”究竟是什么,“run”是什么?sombody plz解释了setRunning(boolean run)方法。

2 个答案:

答案 0 :(得分:0)

run将保存您传递的任何内容作为setRunning()方法的参数。它将是truefalse

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

修改

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

请参阅here

答案 1 :(得分:0)

skbishi,只有在画布到位且精灵设置完毕后才能运行才能启动GameLoopThread?