温馨提示×

java sleep方法如何使用

小亿
115
2023-08-24 09:22:22
栏目: 编程语言

在Java中,可以使用Thread的sleep()方法来暂停当前线程的执行。该方法有两种重载形式:

  1. public static native void sleep(long millis) throws InterruptedException:使当前线程休眠指定的毫秒数。

  2. public static void sleep(long millis, int nanos) throws InterruptedException:使当前线程休眠指定的毫秒数和纳秒数。

例如,要使当前线程休眠2秒,可以使用以下代码:

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

注意,在使用sleep()方法时,需要处理InterruptedException异常。当其他线程中断当前线程时,会抛出InterruptedException异常。可以选择抛出异常,也可以选择捕获并处理异常。

0