Threads can be paused for a specified time. This makes the processor time available to other threads.
The sleep
method of the Thread
class takes the sleep period
in milliseconds or in milliseconds and nanoseconds.
For example, the Thread.sleep(5_000)
pauses the thread for 5000 milliseconds, which is 5 seconds.
Important to mention, this time period cannot be considered to be exact.
It depends on the OS how precisely can handle it.
The sleep
method throws InterruptedException
.
This is important when a thread should be interrupted.
To learn more about thread interruption, see the
Thread Interruption page.
In the next example, the throws clause is just added to the main method.
In the ThreadSleep
class, the main thread is paused for 5 seconds.
The current time is printed out before and after the sleep
method.
package com.programcodex.concurrency.thread;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class ThreadSleep {
public static void main(String[] args) throws InterruptedException {
printTime();
Thread.sleep(5_000);
printTime();
}
private static void printTime() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println(dtf.format(LocalTime.now()));
}
}
The output of the above class: