Open In App

How to Make a Java Thread Sleep for a Specific Duration?

Java is one of the famous programming languages for developing Real-time Applications. The Thread is a small unit of execution within a process, the Thread shares resources like files and memories with other threads in the same processor.

For this, we have used Thread.sleep() method. This method takes several milliseconds. The Thread should sleep as an argument. In this article, we will learn how to make a Java thread sleep for a specific duration.



Syntax:

Thread.sleep(numberOfSeconds);

Program to make a Java thread sleep for a specific duration

In this example, we have created one Java Class. Then in the main method, we created a try-catch block. In that block, we have created one Thread.sleep() before this try-catch block. Once the program is running First, we get output as Thread is going to sleep for 5 seconds… After this, the thread sleeps until 5 seconds. After 5 seconds the second print is executed.

Let us go through the implementation below:






// Java program to make a thread sleep for a specific duration 
import java.io.*;
public class ThreadExample 
{
    public static void main(String[] args) 
    {
        System.out.println("\nThread is going to sleep for 5 seconds...");        
        try {
            // sleep for 5 seconds
            Thread.sleep(5000); // 5000 milliseconds = 5 seconds
        } catch (InterruptedException e) {
            // handle interrupted exception if needed
            e.printStackTrace();
        }
          
        System.out.println("Thread woke up after sleeping for 5 seconds.\n");
    }
}

Output
Thread is going to sleep for 5 seconds...
Thread woke up after sleeping for 5 seconds.


Explanation of the above Program:

In the above program,

Article Tags :