Java 如何为while循环添加延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25166215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:46:36  来源:igfitidea点击:

How to add delay to while loop

java

提问by user3910313

I have a while loop and what I want it to do is every 1 second count up an integer up to 10. The code that I have now simply spits out 1-10 as quick as it possibly can with no delay, I'm un-sure how to add a delay. package apackage;

我有一个 while 循环,我想要它做的是每 1 秒计算一个整数,最多为 10。我现在的代码只是尽可能快地吐出 1-10,没有延迟,我不-确定如何添加延迟。包一个包;

public class loops {
    public static void main(String args[]){
        int countdown = 1;
        while (countdown < 10) {
            System.out.println(countdown);
            ++countdown;
        }
    }
} 

So, thanks for reading and appreciate the help in advance.

所以,感谢您的阅读并提前感谢您的帮助。

采纳答案by odlund

Change your code to this

将您的代码更改为此

public class loops {
    public static void main(String args[]) throws InterruptedException {
        int countdown = 1;
        while (countdown < 10){
            System.out.println(countdown);
            ++countdown;
            Thread.sleep(1000);
        }
    }
} 

回答by JerryDeveloper

You may consider Thread.sleep()

你可以考虑 Thread.sleep()

Hereis the tutorial

是教程

回答by barak manos

Add this at the beginning of the loop:

在循环的开头添加:

long time = System.currentTimeMillis();

And add this at the end of the loop:

并在循环末尾添加:

long wait = time + 1000 - System.currentTimeMillis();
if (wait > 0)
    Thread.sleep(wait);