5.6 Pausing Execution With Sleep Interrupts
5.6 Pausing Execution With Sleep Interrupts
Java provides mechanisms for controlling thread execution using sleep() and interrupts.
These are useful for pausing execution, managing concurrency, and handling
interruptions in multi-threaded applications.
Thread running: 1
(Thread pauses for 1 second)
Thread running: 2
(Thread pauses for 1 second)
...
🚀 Key Points:
sleep() temporarily pauses the thread, allowing other threads to execute.
It does not release locks, so it can still hold resources.
Throws InterruptedException if another thread interrupts it while sleeping.
try {
Thread.sleep(3000); // Main thread waits for 3 seconds
t1.interrupt(); // Interrupt t1 while sleeping
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
✅ Output (Thread gets interrupted while sleeping):
Running: 1
Running: 2
Thread was interrupted while sleeping!
🚀 Key Points:
interrupt() signals a thread that it should stop.
If a thread is sleeping or waiting, an InterruptedException is thrown.
If a thread is not sleeping, interrupt() only sets a flag (isInterrupted()).
try {
Thread.sleep(3000); // Main thread waits for 3 seconds
t1.interrupt(); // Interrupt the thread
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
✅ Output:
Thread is running...
Thread is running...
Thread is running...
Thread interrupted! Stopping execution.
🚀 Key Points:
isInterrupted() returns true if the thread was interrupted.
If an InterruptedException occurs, the interrupt flag is cleared.