我現在正在學習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仍然會自增。
任何幫助解釋這將有助於,謝謝!
它看起來像任何處理程序是每次重新調度它 – lhoworko
「postDelayed()」的第一個參數是一個「Runnable」 - 它只是重新執行它的內部('this')'Runnable'直到j是4。 – PPartisan