在 Java 中,可以使用 Thread.sleep() 方法来让程序休眠一段时间,然后再进行下一次循环。以下是一个每隔 1000 毫秒执行一次循环的示例代码:

public class Main {
    public static void main(String[] args) {
        int count = 0;
        while (true) {
            // 执行循环体的代码
            System.out.println('循环次数:' + count);
            
            try {
                // 休眠 1000 毫秒
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            count++;
        }
    }
}

上述代码中使用了一个无限循环,每次循环都会输出当前循环次数,并在循环结束后休眠 1000 毫秒。你可以根据需要在循环体中加入你要执行的代码。


原文地址: https://www.cveoy.top/t/topic/qhpG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录