How to set time intervals in Java?

In Java, you can use the Thread.sleep() method to set a time interval. The method takes a parameter in milliseconds to indicate the duration for which the thread will pause its execution.

Here is an example code demonstrating how to set the time interval to 1 second.

public class Main {
    public static void main(String[] args) {
        try {
            // 设置时间间隔为1秒
            long interval = 1000;

            // 执行代码
            System.out.println("开始执行");
            Thread.sleep(interval);
            System.out.println("暂停" + interval + "毫秒后继续执行");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

In the above code, the Thread.sleep(interval) method will pause the current thread’s execution for a specified amount of time, measured in milliseconds. In the example, the thread will pause for 1 second before continuing to execute and output the corresponding message.

It should be noted that the Thread.sleep() method may throw an InterruptedException, so proper exception handling is required.

bannerAds