Java 每隔 1000 毫秒执行代码 - 使用 Thread.sleep() 方法
您可以使用 Java 中的 Thread.sleep() 方法来实现每隔 1000 毫秒执行一次代码。可以按照以下方式编写代码:
public class Main {
public static void main(String[] args) {
while (true) {
try {
// 执行需要重复执行的代码
System.out.println('执行代码');
// 线程休眠 1000 毫秒
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
在上述示例中,Thread.sleep(1000) 将使当前线程休眠 1000 毫秒,然后代码将继续执行,实现了每隔 1000 毫秒执行一次代码的效果。
原文地址: https://www.cveoy.top/t/topic/qhpE 著作权归作者所有。请勿转载和采集!