Java - Thread Thread Sleep


Thread class static sleep() method makes a thread sleep for a specified duration.

It accepts a timeout as an argument.

You 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 an object's lock before sleeping, it would hold the locks.

sleep() method throws a java.lang.InterruptedException and your code should handle it.

The following code demonstrates the use of the Thread.sleep() method.


public class Main {
  public static void main(String[] args) {
    try {//from   ww  w.  j a v  a2s  .  c o m
      System.out.println("I am going to sleep for 5 seconds.");
      Thread.sleep(5000); // The "main" thread will sleep
      System.out.println("I woke up.");
    } catch (InterruptedException e) {
      System.out.println("Someone interrupted me in my sleep.");
    System.out.println("I am done.");


Related Topics