2017-08-09 133 views
0

我现在正在学习Runnable,并且对我发现的代码以及它的运行方式有点困惑。Android Java - Runnable混淆

j = 0; 
public Runnable test = new Runnable() { 
    @Override 
    public void run() { 

     if (j <= 4) { //this is an if statement. shouldn't it run only once? 
      Log.i("this is j", "j: " + j); 
      handler.postDelayed(this, 2000); //delays for 2 secs before moving on 
     } 

     j++; //increase j. but then why does this loop back to the top? 

     Log.i("this is j", "incremented j: " + j); 
    } 
}; 

当我运行此,每2秒Ĵ将记录从0到4,我不明白为什么,虽然,但它正是我需要为每2秒更新一次数据。

运行()只是保持...运行?这将解释为什么它保持循环,有点。但是,如果情况是这样,那么即使在if语句结束之后,j仍然会自增。

任何帮助解释这将有助于,谢谢!

+2

它看起来像任何处理程序是每次重新调度它 – lhoworko

+0

“postDelayed()”的第一个参数是一个“Runnable” - 它只是重新执行它的内部('this')'Runnable'直到j是4。 – PPartisan

回答

3

退房the documentation for Handler.postDelayed(Runnable, long)

导致要被添加到消息队列中的可运行R,经过指定的时间量之后运行。

postDelayed()做什么是采取Runnable实例,并给定延迟后调用它run()方法。它确实从而不是在你离开的地方继续执行。

在你的情况,你是路过this这是一个Runnable,检查if (j <=4))如果是的话,同样可运行一遍,从而再次执行run()方法的帖子。

如果您在检查j <= 4之后是否想要延迟,那么您可能希望Thread.sleep()在给定的时间段内睡眠一个线程。

2

一个Runnable就是这样:一段可以运行的代码。当你在Handler中使用Runnable时,就会发生这种奇迹,就像你在这里做的那样。 Handler将接受Runnable's并在Handler的线程上调用它们的run()方法。你告诉Handler使用Hander.post()或Handler.postDelayed()来运行Runnable。 post()立即运行Runnable,postDelayed()在给定的毫秒数后运行它。

所以run()方法只运行一次,但此行:

handler.postDelayed(this, 2000); 

告诉处理程序安排运行(即,这个Runnable接口)后,2000毫秒(2秒)。