Lesson 44
Thread sleep() Method
sleep() pauses the current thread for a set duration, then resumes automatically.
Java Track
Save progress as you learn.
61 lessons
Lesson content
sleep() suspends the current thread for a given duration. After the time expires, the thread resumes automatically.
Definition List
- sleep(): Static Thread method that pauses the current thread.
- Sleeping Thread: Inactive thread waiting for sleep to expire.
- InterruptedException: Thrown when a sleeping thread is interrupted.
- Current Thread: The thread currently executing code.
sleep() Syntax
// Pause for milliseconds
Thread.sleep(milliseconds);
// Example — pause for 1 second
Thread.sleep(1000);Thread State During sleep()
Runnable
↓
Timed Waiting (sleep)
↓
RunnableExample 01: Using sleep() Method
package com.java.Multi_threading;
public class SleepExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Countdown: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Time's up!");
}
}Output
Countdown: 1
Countdown: 2
Countdown: 3
Countdown: 4
Countdown: 5
Time's up!Handling InterruptedException
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}sleep() vs wait()
- sleep() — Thread class. Does not release locks.
- wait() — Object class. Releases lock. Needs synchronization.
- Both throw InterruptedException.
- sleep() pauses; wait() coordinates thread communication.
Best Practices
- Keep sleep durations reasonable.
- Always handle InterruptedException.
- Don't use sleep() for synchronization.
- Account for system-dependent sleep variance.
FAQ
1. What does sleep() do in Java?
Pauses the current thread for a specified time.
2. Which thread does sleep() affect?
Only the currently executing thread.
3. Why does sleep() throw InterruptedException?
Another thread interrupted it during sleep.
Where Java is used
Java in real-world development
sleep() Syntax
Thread.sleep(milliseconds). Accepts a long value. Throws InterruptedException.
Timed Waiting State
Thread enters this state during sleep, then returns to Runnable.
InterruptedException
Thrown when another thread interrupts a sleeping thread. Must be caught.
Locks During sleep()
sleep() holds any synchronized locks. It does not release them.
sleep() vs wait()
sleep() is from Thread, holds locks. wait() is from Object, releases locks.
Common Uses
Delays, countdowns, simulating processing time, multithreading demos.