What is the use of Thread.sleep() method in Java?


The sleep() method is a static method of Thread class and it makes the thread sleep/stop working for a specific amount of time. The sleep() method throws an InterruptedException if a thread is interrupted by other threads, that means Thread.sleep() method must be enclosed within the try and catch blocks or it must be specified with throws clause.

Whenever we call the Thread.sleep() method, it can interact with the thread scheduler to put the current thread to a waiting state for a specific period of time. Once the waiting time is over, the thread changes from waiting state to runnable state.

Syntax

public static void sleep(long milliseconds)
public static void sleep(long milliseconds, int nanoseconds)

The sleep(long milliseconds) method makes a thread to sleep for some specific milliseconds only.

The sleep(long milliseconds, int nanoseconds) method makes a thread to sleep for some specific milliseconds plus nanoseconds.

Example

class UserThread extends Thread {
   public void run() {
      for(int i=1; i <= 5; i++) {
         System.out.println("User Thread");
         try {
            Thread.sleep(1000); // sleep/stop a thread for 1 second
         } catch(InterruptedException e) {
            System.out.println("An Excetion occured: " + e);
         }
      }
   }
}
public class SleepMethodTest {
   public static void main(String args[]) {
      UserThread ut = new UserThread();
      ut.start(); // to start a thread
   }
}

Output

User Thread
User Thread
User Thread
User Thread
User Thread

Updated on: 27-Nov-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements