java中sleep方法怎么调用
在Java中,可以使用Thread类的sleep方法来使当前线程暂停执行一段时间。调用sleep方法的方式如下:
- 使用Thread类的静态方法sleep,指定暂停的时间(单位为毫秒):
try {
Thread.sleep(1000); // 暂停1秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
- 在实现Runnable接口的类中,可以使用Thread类的实例方法sleep,指定暂停的时间(单位为毫秒):
class MyRunnable implements Runnable {
public void run() {
try {
Thread.sleep(1000); // 暂停1秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
// ...
}
}
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
注意:在调用sleep方法时,可能会抛出InterruptedException异常,需要进行异常处理。
原文地址: https://www.cveoy.top/t/topic/bFPO 著作权归作者所有。请勿转载和采集!