Java Thread sleep and interrupt methods.
Thread Sleep
- The
sleep
method is a method in theThread
class in Java that allows a thread to pause its execution for a specified amount of time. - This method is useful when a thread needs to wait for some external event or to introduce a delay in the execution of the thread.
- The
sleep
method can be interrupted by another thread using theinterrupt
method, which causes thesleep
method to throw anInterruptedException
.(it jumps to the catch block directly) - One advantage of using
sleep
is that it allows for a predictable delay in the execution of a thread. However, a disadvantage is that it can potentially cause issues with concurrency and performance if not used carefully.
Special Note-
calling the sleep
method inside a locked block of code does not release the lock held by the thread. The lock will be held by the thread until the synchronized block of code completes, even if the thread is sleeping inside that block of code.
For example, consider the following Java code:
synchronized (lock) {
// Do some synchronized work here
Thread.sleep(1000); // Sleep for 1 second
// Do some more synchronized work here
}
In this code, the thread acquires the lock held by the lock
object before entering the synchronized block of code. If the thread calls sleep
inside the synchronized block, it will continue to hold the lock while sleeping for 1 second. Once the sleep finishes, the thread will continue executing the remaining synchronized code before releasing the lock at the end of the synchronized block
Sure, here’s a summary of what thread sleep and interrupt are, their practical usage, and their advantages and disadvantages:
Thread Interrupt
- The
interrupt
method is a method in theThread
class in Java that allows one thread to interrupt another thread that is currently executing. - This method is useful when a thread needs to stop or interrupt another thread that is taking too long to complete, or when a thread needs to notify another thread to stop what it’s doing and do something else instead.
- Interrupting a sleeping thread will cause the
sleep
method to throw anInterruptedException
immediately, allowing the thread to stop sleeping and handle the interruption. - One advantage of interrupting a thread is that it allows for better control over the execution of a program, as threads can be stopped or interrupted as needed. However, a disadvantage is that it can potentially introduce issues with thread safety and synchronization if not used carefully.
In general, sleep
and interrupt
should be used carefully and thoughtfully to ensure that they don't introduce issues with concurrency and performance in a program. sleep
should be used when a thread needs to wait for some external event or to introduce a delay in execution, while interrupt
should be used when a thread needs to stop or interrupt another thread. Proper synchronization and locking mechanisms should also be used to ensure thread safety and prevent issues with concurrency.
FAQ
Can I pass parameters in sleep ? also in interrupt?
The sleep
method in Java takes a single parameter, which is the duration of time that the thread should sleep for. This duration can be specified in milliseconds using an integer or long value. For example, Thread.sleep(1000)
would cause the current thread to sleep for one second.
The interrupt
method in Java does not take any parameters. It simply interrupts the execution of the target thread, causing it to throw an InterruptedException
if it is currently sleeping or waiting.
A sample Java code where ATM is waits 10 seconds using sleep,till user enters the PIN, before 10 seconds user enters it, thread get interuptted and directly show the main menu.
package com.seepandinterrupt;
import java.util.Scanner;
public class ATM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the ATM! Enter your PIN to proceed");
// Create a new thread to handle the PIN entry with a 10-second sleep
Thread pinThread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10000); // Sleep for 10 seconds
System.out.println("Slept for 10 seconds.");
} catch (InterruptedException e) {
/*
when a thread is interrupted while sleeping, the sleep method will throw an InterruptedException immediately,
and the thread will jump to the catch block that handles this exception.
*/
return;
}
// If we got here, the sleep finished without interruption, so display an error message and exit
System.out.println("Time's up! Please try again.");
System.exit(0);
/*
System.exit(0) is a call to the exit method of the System class in Java. This method terminates the currently running Java Virtual Machine (JVM) and stops the execution of the program.
The parameter 0 passed to the exit method is an exit code that can be used to indicate the reason for the program's termination.
*/
}
});
pinThread.start(); // Start the thread
// Wait for the user to input their PIN or interrupt the PIN thread
String pin = "";
while (true) {
if (scanner.hasNextLine()) {
pin = scanner.nextLine();
pinThread.interrupt(); // Interrupt the PIN thread to wake it up
break;
}
}
System.out.println("PIN entered: " + pin);
System.out.println("Main menu:");
// Display the main menu options here
}
}
Output when PIN is entered before 10 seconds
Welcome to the ATM! Enter your PIN to proceed
6789
PIN entered: 6789
Main menu:
Process finished with exit code 0
Output when PIN is not entered before 10 seconds
Welcome to the ATM! Enter your PIN to proceed
Slept for 10 seconds.
Time's up! Please try again.
Process finished with exit code 0
Further FAQ-differences between Thread.sleep and Object.wait: