Android Java-可运行的混乱
我现在正在学习Runnable,对我找到的代码和它的运行方式有点困惑Android Java-可运行的混乱,java,android,runnable,Java,Android,Runnable,我现在正在学习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);
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);
}
};
j=0;
公共可运行测试=新可运行(){
@凌驾
公开募捐{
如果(j检查:
使可运行r添加到消息队列中,在经过指定的时间后运行
postDelayed()
所做的是获取一个Runnable
实例,并在给定的延迟后调用其run()
方法。它不会在您停止的地方继续执行
在您的情况下,您正在传递this
,这是一个Runnable
,用于检查是否(j签出:
使可运行r添加到消息队列中,在经过指定的时间后运行
postDelayed()
所做的是获取一个Runnable
实例,并在给定的延迟后调用其run()
方法。它不会在您停止的地方继续执行
在您的例子中,您正在传递this
,这是一个Runnable
,它检查是否(jRunnable就是可以运行的代码块。当您将Runnable与处理程序一起使用时,就像您在这里所做的那样,神奇就会发生。处理程序将接受Runnable并调用它们的run()方法。您可以告诉处理程序使用Hander.post()或Handler.postDelayed()运行可运行程序。post()立即运行可运行程序,postDelayed()在给定的毫秒数后运行
因此run()方法只运行一次,但这一行:
handler.postDelayed(this, 2000);
告诉处理程序计划在2000毫秒(2秒)后运行此(即,此Runnable)。Runnable只是一个可以运行的代码块。当您将Runnable与处理程序一起使用时,就像您在这里所做的那样,魔术就会发生。处理程序将接受Runnable并调用它们的run()方法。您可以告诉处理程序使用Hander.post()或Handler.postDelayed()运行可运行程序。post()立即运行可运行程序,postDelayed()在给定的毫秒数后运行
因此run()方法只运行一次,但这一行:
handler.postDelayed(this, 2000);
告诉处理程序计划在2000毫秒(2秒)后运行此操作(即,此可运行)。每次postDelayed()
的第一个参数用于Runnable
-它只会重新执行它内部的Runnable
(this
)直到j为4。看起来无论处理程序是什么,每次都会重新调度它,postDelayed()
的第一个参数用于Runnable
-它只是重新执行Runnable
它在里面(this
)直到j为4。