温馨提示×

java sleep方法怎么用

小亿
112
2023-09-25 16:22:33
栏目: 编程语言

在Java中,可以使用Thread类的sleep方法来暂停当前线程的执行。该方法有两个重载的版本:

  1. sleep(long millis):使当前线程休眠指定的毫秒数。

  2. 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异常,所以需要进行异常处理。

0