繁体   English   中英

Android Java-可运行的混乱

[英]Android Java - Runnable confusion

我现在正在学习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秒j将从0记录到4。虽然我不明白为什么,但是它确实满足了我每2秒更新一次数据的需求。

run()只是保持运行吗? 这就可以解释为什么它不断循环。 但是,如果是这样的话,那么即使if语句完成后,j仍然会自己增加。

对此的任何帮助都将有所帮助,谢谢!

查看Handler.postDelayed(Runnable, long)的文档

使Runnable r添加到消息队列中,并在经过指定的时间后运行。

postDelayed()作用是获取一个Runnable实例,并在给定的延迟后调用其run()方法。 你离开的地方它不会恢复执行。

在您的情况下,您正在传递this ,它是一个Runnable ,用于检查if (j <=4 )) ,如果是,则再次发布该可运行对象,从而再次执行run()方法。

如果您只是想在检查j <= 4之后是否需要延迟,那么您可能希望Thread.sleep()可以使线程休眠给定的时间。

一个Runnable就是:可以运行的代码块。 当您将Runnable与Handler结合使用时,就像在这里一样,魔术就发生了。 处理程序将接受Runnable,并在处理程序的线程上调用它们的run()方法。 您告诉处理程序使用Hander.post()或Handler.postDelayed()运行Runnable。 post()立即运行Runnable,postDelayed()在给定的毫秒数后运行它。

因此,run()方法仅运行一次,但此行:

handler.postDelayed(this, 2000);

告诉处理程序安排在2000毫秒(2秒)后运行 (即Runnable)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM