我现在正在学习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