java sleep用法
时间: 2024-06-13 16:08:53 浏览: 18
以下是Java中sleep()方法的用法和示例:
sleep()方法是Thread类的一个静态方法,用于使当前线程暂停执行一段时间。它有两个重载方法:
1. public static void sleep(long millis) throws InterruptedException
使当前线程睡眠millis毫秒。
2. public static void sleep(long millis, int nanos) throws InterruptedException
使当前线程睡眠millis毫秒加nanos纳秒。
示例代码如下:
1. 使当前线程睡眠1秒钟
```java
public class MySleepStudy {
public static void main(String[] args) {
long start = System.currentTimeMillis();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(end - start + "毫秒过去了");
}
}
```
2. 使当前线程睡眠1秒钟零100000纳秒
```java
public class MySleepStudy {
public static void main(String[] args) {
long start = System.currentTimeMillis();
try {
Thread.sleep(1000, 100*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(end - start + "毫秒过去了");
}
}
```