簡體   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