簡體   English   中英

在 Java 中的特定時間后執行一段代碼

[英]Execute a block of code after certain time in Java

我想在一段時間后在線程中執行一段代碼。

在線程中:

public void run() {
    System.out.println("it is running");
    while (true) {
        if (System.currentTimeMillis() > lastEdit) {
            System.out.println("DELETE");
            timerStart(12000);
        }
    }
}

public static void timerStart(int time) {
    lastEdit = System.currentTimeMillis() + time;
}

在這段代碼中,System.out.println("DELETE") 將在 12 秒后執行。 但是,我也會在另一個代碼中調用 timeStart function,如下所示

anotherThread.timerStart(12000);

當我調用這個 function 時,我預計 lastEdit 將增加 12000 毫秒。 但是,它不起作用。 我可以知道為什么以及如何解決這個問題嗎? 謝謝。

不確定我明白你真正想做什么,但改變你的run() function 讓它大部分時間“睡覺”可能會提高你程序的性能:

public void run() {
    System.out.println("it is running");
    while(true) {
        long timeUntilDelete = lastEdit - System.currentTimeMillis();
        if (timeUntilDelete > 0) {
            try {
                Thread.sleep(timeUntilDelete);
            }
            catch(InterruptedException ex) {
                ...What you do here is up to you...
            }
            continue;
        }
        System.out.println("DELETE");
        timerStart(12000);
    }
}

您好,您可以使用ScheduledExecutorService ,看看 oracle 文檔,您會找到一個示例,我相信可以解決您的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM