2017-08-09 137 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秒)。