How to pause the current thread using sleep method in java

This example shows you how to pause the thread using sleep method of thread class in java.

You can pause a current thread for a number of milliseconds by using the sleep() method of the Thread class. While the current thread is sleeping, the thread will be resuming after completing the mentioned milliseconds in sleep method. This will allow other threads to execute.

Below is the example of using sleep method in java

package com.java.connect.thread;
 
//How to pause the current thread using sleep method in java
public class ThreadSleepExample implements Runnable {
 
    // implement the run method
    public void run() {
        System.out.println("Starting thread");
        try {
            // Call the sleep method to pause the thread,
            // Here we are putting to wait for 5 seconds
            Thread.sleep(5000);
            System.out.println("Pause for 5 seconds");
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println("Ending thread");
    }
 
    public static void main(String[] args) {
        // Create the thread
        Thread thread = new Thread(new ThreadSleepExample());
        // Start the thread
        thread.start();
    }
}

The output of the above example will be as:

Starting thread
Pause for 5 seconds
Ending thread