Java Thread sleep() Method
Example
Print a number every second:
public class Main {
public static void main(String[] args) throws InterruptedException {
for (int i = 1; i <= 3; i++) {
System.out.println(i);
Thread.sleep(1000);
}
}
}
Definition and Usage
The sleep() method pauses the current thread (the thread that runs the code) for the specified number of milliseconds. 1000 milliseconds is one second.
It is a static method, so you call it on the class: Thread.sleep(1000). You must catch the InterruptedException or add throws InterruptedException to the method, like in the example.
Syntax
One of the following:
public static void sleep(long millis) throws InterruptedException
public static void sleep(long millis, int nanos) throws InterruptedException
Parameter Values
| Parameter | Description |
|---|---|
| millis | Required. The number of milliseconds (thousandths of a second) to sleep. |
| nanos | Optional. Extra nanoseconds (billionths of a second) to sleep, from 0 to 999999. |
Technical Details
| Throws: | InterruptedException - if another thread interrupts the thread while it sleeps. IllegalArgumentException - if millis is negative. |
|---|
Related Pages
❮ Thread Methods