How to set the interval time for a loop in Java?

In Java, you can use the sleep() method of the Thread class to set the interval time for a loop to execute. This method will make the current thread sleep for the specified number of milliseconds.

The sample code is as follows:

public class Main {
    public static void main(String[] args) {
        // 设置循环次数
        int loopCount = 10;
        // 设置间隔时间,单位为毫秒
        long interval = 1000;

        for (int i = 0; i < loopCount; i++) {
            // 执行循环体的代码

            try {
                // 线程睡眠指定的时间
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

In the example above, the code in the loop will be executed 10 times with a 1-second interval between each iteration. You can adjust the number of loops and interval time as needed.

bannerAds