thread .sleep
时间: 2023-08-30 16:10:28 浏览: 103
Thread.sleep() is a method in Java that causes the current thread to pause execution for a specific amount of time. It is used to introduce a delay or pause in the execution of a program.
The syntax for Thread.sleep() is:
```java
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
// Handle the exception
}
```
Here, the parameter milliseconds specifies the amount of time in milliseconds that the thread should sleep. The catch block is used to handle the InterruptedException that may be thrown if the thread is interrupted while it is sleeping.
For example, if we want to pause the execution of a program for 1 second, we can use Thread.sleep(1000) like this:
```java
try {
Thread.sleep(1000); // Pause execution for 1 second
} catch (InterruptedException e) {
// Handle the exception
}
```
Note that Thread.sleep() is a static method, so it can be called directly on the Thread class without creating an instance of the class.
阅读全文