🧠 What Does “Putting a Thread to Sleep” Mean?
It means pausing the execution of the current thread for a specific period of time, without releasing any locks it may hold.
This is done using:
Thread.sleep(milliseconds);
Optionally:
Thread.sleep(milliseconds, nanoseconds);
🔄 What Happens During Thread.sleep()
?
- The current thread stops running.
- The thread enters the TIMED_WAITING state.
- After the sleep time is up, it becomes runnable again — meaning it’s eligible to run when the CPU allows it.
- The thread does not lose any monitors (locks) it held before sleeping.
✅ Example
public class SleepExample {
public static void main(String[] args) {
System.out.println("Thread starts...");
try {
Thread.sleep(2000); // sleep for 2 seconds
} catch (InterruptedException e) {
System.out.println("Sleep interrupted!");
}
System.out.println("Thread resumes.");
}
}
🕒 Output:
Thread starts...
(wait 2 seconds)
Thread resumes.
⚠️ Important Notes
Rule/Note | Description |
---|---|
Only affects current thread | Thread.sleep() always pauses the currently running thread |
Doesn’t release locks | If you’re inside a synchronized block, you still hold the lock |
Can be interrupted | Throws InterruptedException if another thread interrupts it |
Doesn’t guarantee wake-up time | It will sleep at least the given time, but might take longer due to thread scheduling |