在Java中,可以使用Thread类的sleep方法来暂停当前线程的执行。该方法有两个重载的版本:
sleep(long millis):使当前线程休眠指定的毫秒数。
sleep(long millis, int nanos):使当前线程休眠指定的毫秒数和纳秒数。
以下是使用sleep方法的示例:
public class SleepExample {
public static void main(String[] args) {
System.out.println("开始执行");
try {
// 休眠3秒
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行完毕");
}
}
在上面的示例中,程序会休眠3秒钟,然后继续执行后面的代码。其中,Thread.sleep方法可能会抛出InterruptedException异常,所以需要进行异常处理。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: 在java中毫秒时间戳如何存储更高效