The Thread class contains a static sleep() method, which makes a thread sleep for a specified duration.
Thread.sleep() method accepts a timeout as an argument.
We can specify the timeout in milliseconds, or milliseconds and nanoseconds. The thread that executes this method sleeps for the specified amount of time.
A sleeping thread is not scheduled by the operating system scheduler to receive the CPU time.
If a thread has the ownership of a lock before it goes to sleep, it continues to hold those locks during the sleep.
The sleep() method throws a java.lang.InterruptedException and your code has to handle it.
The following code demonstrates the use of the Thread.sleep() method.
public class Main { public static void main(String[] args) { try {/*from w w w . j a v a 2 s .c o m*/ System.out.println("sleep for 5 seconds."); Thread.sleep(5000); // The "main" thread will sleep System.out.println("woke up."); } catch (InterruptedException e) { System.out.println("interrupted."); } System.out.println("done."); } }
The code above generates the following result.
TimeUnit enum in the java.util.concurrent package represents a measurement of time in various units such as milliseconds, seconds, minutes, hours, days, etc.
It has the sleep() method which works the same as the Thread.sleep().
We can use the sleep() method of TimeUnit instead to avoid the time duration conversion:
TimeUnit.SECONDS.sleep(5); // Same as Thread.sleep(5000);
Full source code
import java.util.concurrent.TimeUnit; /*from w w w . j ava 2 s . c o m*/ public class Main { public static void main(String[] args) { try { System.out.println("sleep for 5 seconds."); TimeUnit.SECONDS.sleep(5); // Same as Thread.sleep(5000); // The "main" thread will sleep System.out.println("woke up."); } catch (InterruptedException e) { System.out.println("interrupted."); } System.out.println("done."); } }
The code above generates the following result.