How to PROPERLY add sleep in Java? [SOLVED]


JAVA, Java Examples

Author: Bashir Alam
Reviewer: Deepak Prasad

Java sleep is a method used to pause the execution of a thread for a specified amount of time. It is used when you want to introduce a delay in your program or when you want to give other threads a chance to execute. In this short article, we will discuss what is java sleep. Moreover, we will cover some examples of java sleep.

 

What is Java Sleep? When should we use it?

Java sleep is a method used to pause the execution of a thread for a specified amount of time. It is one of the built-in methods in the Thread class in Java and is used when you want to introduce a delay in your program or when you want to give other threads a chance to execute.

The sleep() method takes a single argument, which is the number of milliseconds for which you want to pause the thread. The method can throw an InterruptedException, which is a checked exception that is thrown when another thread interrupts the sleeping thread.

The syntax of Java sleep is shown below:

public static void sleep(long millis) throws InterruptedException

The sleep() method takes a single argument, which is the number of milliseconds for which you want to pause the thread. The method can throw an InterruptedException, which is a checked exception that is thrown when another thread interrupts the sleeping thread.

When you call the sleep() method, the thread that calls it is paused for a specified amount of time. The thread remains in the WAITING state during sleep time. After the sleep time has elapsed, the thread transitions back to the RUNNABLE state and continues executing from where it left off.

Here are some common use cases of the Java sleep() method:

  1. Introducing a delay: You may want to introduce a delay in your program for various reasons, such as waiting for user input or simulating a slow process. In such cases, you can use the sleep() method to pause the execution of the thread for the desired amount of time.
  2. Giving other threads a chance to execute: In a multi-threaded program, you may have multiple threads running concurrently. Sometimes, you may want to give other threads a chance to execute by pausing the current thread. You can use the sleep() method to pause the current thread and allow other threads to execute.
  3. Animation: If you are developing a graphical user interface (GUI) application, you may want to create animations that involve pausing the execution of a thread for short periods of time. In such cases, you can use the sleep() method to pause the thread for a short period of time between each frame of the animation.

 

How Java sleep works

When you call the Java sleep() method, the thread that calls it is paused for the specified amount of time. The sleep() method essentially puts the thread into a waiting state for the specified time period.

When a thread is in the waiting state, it is not executing any code and is not consuming any CPU resources. Instead, the thread is waiting for a certain event to occur before it can resume execution.

Under the hood, the sleep() method uses the operating system's timer facilities to wait for the specified time period. When the sleep() method is called, it sets a timer that expires after the specified time period has elapsed. The thread is then blocked until the timer expires.

While a thread is sleeping, it can be interrupted by another thread. When a thread is interrupted, it throws an InterruptedException, which can be caught by the calling code. The InterruptedException is a checked exception, which means that it must be caught or declared to be thrown by the calling method.

It is worth noting that the sleep() method does not guarantee precise timing. The actual time period for which the thread is paused may be longer or shorter than the specified time period, depending on various factors such as the operating system's timer resolution and the thread scheduler's behavior.

Here is an example of how the Java sleep() method works:

public class Main {
    public static void main(String[] args) {
        System.out.println("Starting the program...");
        try {
            System.out.println("Pausing the thread for 5 seconds...");
            Thread.sleep(5000); // Pause the thread for 5 seconds
            System.out.println("Thread resumed after 5 seconds.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Program completed.");
    }
}

Output:

Starting the program...
Pausing the thread for 5 seconds...
Thread resumed after 5 seconds.
Program completed.

In this example, the sleep() method is called with a parameter of 5000 milliseconds, which corresponds to a 5-second pause. As you can see, the program pauses for approximately 5 seconds before resuming execution. During this time, the thread is in a waiting state, and no code is executed. Once the sleep time has elapsed, the thread resumes execution and continues with the next statement.

 

Example-1: Pause for a specified period of time

We can use the sleep method to pause for a specific period of time as shown below:

public class Main {
    public static void main(String[] args) {
        System.out.println("Starting the program...");
        try {
            Thread.sleep(5000); // Pause the thread for 5 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Program completed.");
    }
}

This example demonstrates how to use the Java sleep() method to pause the execution of a thread for a specified period of time. In this case, the sleep() method is called with a parameter of 5000 milliseconds, which corresponds to a 5-second pause. During sleep time, the thread is in a waiting state and no code is executed. After the sleep time has elapsed, the thread resumes execution and the "Program completed." message is printed.

 

Example-2: Pause and check for interrupt

Now we will take an example to see how we can use the sleep method to check for any interruption.

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                System.out.println("Pausing the thread for 10 seconds...");
                Thread.sleep(10000); 
                System.out.println("Thread resumed after 10 seconds.");
            } catch (InterruptedException e) {
                System.out.println("Thread interrupted!");
            }
        });
        thread.start();
        try {
            Thread.sleep(5000); 
            thread.interrupt(); 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

This example demonstrates how to use the Java sleep() method in conjunction with thread interruption. The main thread starts a new thread, which then calls the sleep() method with a parameter of 10000 milliseconds, corresponding to a 10-second pause. The main thread then sleeps for 5 seconds and interrupts the other thread. When the other thread wakes up, it checks for the interrupt status and handles it by printing a message.

 

Bonus Tip

There are a few potential problems that can arise when using the Thread.sleep() method in Java:

  1. Interrupted Exceptions: When calling Thread.sleep(), you need to handle InterruptedException, which can be thrown if another thread interrupts the sleeping thread. This can make code more complex and error-prone.
  2. Inaccurate Timing: The actual duration of the sleep may be longer or shorter than the specified duration due to the system's scheduling behavior. This can make precise timing of code execution difficult.
  3. Blocking: When a thread calls Thread.sleep(), it blocks execution of that thread, which can cause performance issues if multiple threads are sleeping at the same time.
  4. Unpredictable behavior: If you use Thread.sleep() too frequently or for too long, it can cause unpredictable behavior in your program. For example, if you sleep the main thread for too long, the GUI of your application may appear to hang or freeze, which can lead to a poor user experience.

 

Summary

The Java sleep() method allows a thread to pause its execution for a specified amount of time, putting the thread into a waiting state. In this short article, we discussed how we can use java sleep to pause the program by taking various examples.

 

Further Reading

Java sleepĀ 

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment