等待一定分钟数以检查条件是否为真的代码



我在下面编写了此示例代码,我希望代码检查条件是否为真,如果为假,则等待几分钟再次检查条件是否为真并重复相同的过程,直到条件为真,然后继续另一行代码。在条件为真之前,我不希望代码在代码下面执行。我知道代码是基本的,但它只是一个示例。

import java.util.concurrent.TimeUnit;
public class Program {
    public static void main(String[] args) {
        int me = 1;
        int you = 19;
        int we = 36;
        boolean found = false; 
        while (!found) {
            // where to input the TimeUnit for the code to check again if one of the conditions are true so it can move on to the next line of code if there is any?
            // TimeUnit.MINUTED.sleep(15);
            if(me > you){
                System.out.println("I am greater");
                found = true;
            }
            else if(you > we){
                System.out.println("(lesser)");
            }
            else if(we < me){
                System.out.println("fine");
            }
        }
    }
}

我认为你需要一个计时器来实现这一目标。

这里有一个参考可能会帮助你设置它:如何在 Java 中设置 Timer

首先,您需要某种条件才能更改指定变量的值。即使你放了一个计时器,你也只会进入一个无限循环。一个简单的解决方案是只增加其中一个 if 语句中的一个变量。

您的主要问题的合适答案可以在这里找到:停止代码,直到满足条件

最新更新