Sleeping Thread in Java

Thread sleeping, essentially, is the deliberate pause or suspension of a thread’s execution for a specified duration. This seemingly counterintuitive practice might raise eyebrows, as the idea of voluntarily idling a thread contradicts the instinct to keep all processing units fully engaged.

However, understanding when and how to employ thread sleeping can unlock a myriad of benefits, ranging from improved CPU utilization and power efficiency to mitigating contention for shared resources.

Sleep Method in Java

Method Signature:

1. public static void sleep(long millis) throws InterruptedException

2. public static void sleep(long millis, int nanos) throws InterruptedException

Parameters:

Millis: The amount of time, in milliseconds, that the current thread should sleep (pause). It represents the duration for which the thread will be inactive.

Nanos: The additional time, in nanoseconds, for fine-grained timing control. This parameter could represent a fractional portion of the sleep time.

Return Type:

Void: The sleep() method does not return any value. Once the specified duration (millis) has elapsed, the thread resumes its execution.

Exception:

InterruptedException: The sleep() method can throw an InterruptedException if the thread is interrupted while it is sleeping. This can occur if another thread calls the interrupt() method on the sleeping thread, indicating a request for it to terminate its sleeping state. The exception provides a mechanism for handling thread interruption gracefully.

Functionality:

The sleep() method is used to temporarily pause the execution of the current thread. It causes the thread to enter a “timed waiting” state, during which it does not consume CPU resources. This is commonly used to introduce delays, control timing, or manage concurrency in Java applications. The sleep() method is often employed to simulate real-world scenarios, implement timing-related functionality, or ensure proper synchronization among threads.

The main takeaways are as follows:

Time precision: thread.sleep() provides a sleep interval of milliseconds. However, due to the schedule and time resolution of the underlying system, real sleep duration may not be precise. The thread may take a while longer than planned to wake up.

InterruptedException: Another thread can interrupt a thread when it’s asleep. THREAD.sleep() will issue an interruptedException if this is the case. Appropriate handling of exceptions is required to deal with interruptions properly.

Concurrency control: Sleeping a thread can be used to synchronize operations, such as setting time-based schedules, throttling or creating delays in certain tasks.

Procedural cases: In the case of sleep a thread, there are common situations for introducing automatic delayse.g., animation, simulation, transposing Time Sensitive Operations or extending pauses in simultaneous tasks to cope with race conditions and resource contentions.

Consideration: The use of Thread.sleep() in timecritical or performance critical applications should be monitored because it may have a significant impact on the responsiveness and overall behaviour of the system.

Single Thread Sleep: Thread.sleep() affects the currently executing thread only and has no impact on other threads running in the system.

Thread’s Life Cycle with sleep() :

Thread’s-Life-Cycle

New Thread: The thread is in the “New” state after it has been created but before it is started. The thread’s properties, such as priority, name, and other attributes, can be set at this stage.

Runnable Thread: The thread enters the “Runnable” state when it’s ready to be executed, and the start() method is called. The thread is eligible to run, but it’s up to the operating system’s scheduler to determine when exactly it gets CPU time. At this stage, the thread may or may not actually start executing immediately.

Running Thread: The thread enters the “Running” state when the operating system’s scheduler assigns CPU time to it. The thread’s run() method is executed, performing its designated tasks.

Sleeping Thread: The thread can enter the “Timed Waiting” state by calling the sleep() method. The sleep() method pauses the thread’s execution for the specified duration. The thread relinquishes its hold on the CPU during this time, allowing other threads to run.

Resuming Thread: After the sleep duration elapses, the sleeping thread returns to the “Runnable” state. It’s placed back into the pool of threads that are eligible to run, waiting for the scheduler to assign CPU time.

Running Thread (Again): Once the thread is given CPU time by the scheduler, it resumes its execution from where it was paused due to the sleep() method.

Terminated Thread: The thread enters the “Terminated” state when its run() method completes or if an unhandled exception occurs. The thread’s execution comes to an end, and its resources are released.

Example Program:

1.When the sleep() called with custom created thread:

  public class Main {
    public static void main(String[] args) {
    	MyThread t=new MyThread();
    	t.start();
    }
}
class MyThread extends Thread{
    public void run(){
    	try{
            System.out.println("TechVidvan-Thread");
        	Thread.sleep(2000);
        	System.out.println("TechVidvan's Java tutorial");
    	}
    	catch (InterruptedException e){
        	System.out.println("Thread Interrupted");
    	}
    }
}

Output:

TechVidvan-Thread

TechVidvan’s Java tutorial

Explanation:

The MyThread property extends the Thread class and creates custom thread classes. The code to be executed when a thread starts using the start() method is represented by run().

The thread starts by printing “TechVidvanThread” to the console using System.out.println() in the run method. Then, by calling Thread.sleep(2000), the thread will enter a “sleep” state.

It’ll pause execution for 2000 milliseconds in two seconds. The control returns to the main method, which continues to run while the thread sleeps. The thread begins to run again after the sleeping period of 2 seconds and will print TechVidvan’s Java tutorial into the console.

The thread.sleep() method is capable of throwing an interruptableException, so the catch block shall deal with that exception and then print “Thread Interrupted” if a thread breaks down during sleep.

2.When the sleep() called with Main Thread:

public class Main {
    public static void main(String[] args) {
        System.out.println("Main thread started.");
        for (int i = 1; i <= 5; i++) {
            try {
                // Sleep for 1 second
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Data Flair - Statement " + i);
        }
        System.out.println("Main thread finished.");
    }
}

Output:

Main thread started.

Data Flair – Statement 1

Data Flair – Statement 2

Data Flair – Statement 3

Data Flair – Statement 4

Data Flair – Statement 5

Main thread finished.

Explanation:

In the above program, the sleep() is called on the main Thread. The main thread will print the “Data Flair” statement five times, with a 1-second delay between each statement.

3. when negative value passed as an argument to the sleep():

class SleepExample {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("techvidvan");
        try {
            // Sleep for 2.2 seconds (2200 milliseconds)
            Thread.sleep(-2200);
        } catch (IllegalArgumentException e) {
            System.out.println("timeout value is negative");
        }
        System.out.println("Print statement after delay");
    }
}

Output:

techvidvan

timeout value is negative

Print statement after delay

Explanation:

Using a negative value with Thread.sleep() in Java is not allowed, as the method expects a non-negative value representing the sleep time in milliseconds. It attempts to catch the IllegalArgumentException that is thrown when attempting to use a negative value with Thread.sleep().

Conclusion

In conclusion, the sleep() method in Java is a valuable tool for managing thread execution and synchronization within a multithreaded environment. By temporarily pausing the execution of a thread, it allows other threads to have a chance to run and can be used to introduce delays or control timing in various scenarios, such as animations, simulations, or coordinating tasks.

However, it’s important to use sleep() judiciously and consider potential impacts on overall system performance, responsiveness, and synchronization.