Open In App

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

Last Updated : 21 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// 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,

  • First, we have created one Java Class.
  • Then, in the main function, we have written one print statement this statement indicates before sleep the thread.
  • After this, we define the try-catch block for handling errors while occurs.
  • Then, we have created a thread sleep method until 5 seconds.
  • After this, we have created one more print statement for understanding thread sleep functionality.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads