在Java中,Thread.sleep()方法用于暂停当前线程的执行一段指定的时间。它接受一个以毫秒为单位的参数,表示暂停的时间。
使用方法如下:
- 在try-catch块中使用Thread.sleep()方法:
try { // 暂停当前线程执行500毫秒 Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
- 在方法声明中使用throws InterruptedException抛出异常:
public static void main(String[] args) throws InterruptedException { // 暂停当前线程执行500毫秒 Thread.sleep(500); }
注意:使用Thread.sleep()方法时,需要处理InterruptedException异常,这是因为在休眠期间,可能会有其他线程中断当前线程的休眠。