标志的延迟和循环如何是错误的?

时间:2016-02-10 21:24:18

标签: java

我需要为另一个方法async添加延迟执行 并在flag为false时进入循环

boolean flag = false;

if flag == false > add delay, and try again

if flag == true > stop delay and return

3 个答案:

答案 0 :(得分:2)

通过@ shivam7357扩展示例:

public class test {

    public static void main(String[] args) throws InterruptedException {
        boolean delay = true;
        int counter = 0;
        while (delay) {
            Thread.sleep(1000);//time in millisecond, here 1000 = 1second
            counter++;
            System.out.println("counter is now: " + counter);

            if(counter == 10) {
                delay = false;
            }
        }
        System.out.println("Done");
    }
}

在此示例中,如果delay为false,则while循环将不会继续。所以你需要做的就是睡眠线程,然后检查计数器是否足够高以将delay设置为false,从而打破while循环。

答案 1 :(得分:1)

理解这个例子

public class test {

    public static void main(String[] args) throws InterruptedException {
        boolean delay = true;
        int counter = 0;
        while (true) {
            if(delay == true) {
                Thread.sleep(1000);//time in millisecond, here 1000 = 1second
                counter++;
                System.out.println("counter is now: " + counter);
            }
            if(delay == false) {
                break;
            }
            if(counter == 10) {
                delay = false;
            }
        }
        System.out.println("Done");
    }
}

询问您是否有任何疑问。

答案 2 :(得分:0)

使用Thread.sleep(1000);here's an example