In Java, sleep()
, wait()
, notify()
, and notifyAll()
are key methods used for managing thread execution and synchronization. Each serves a distinct purpose in controlling how threads interact and coordinate.
1. sleep() Method
- Usage:
Thread.sleep(milliseconds)
- Purpose: Pauses the current thread for a specified duration without releasing any locks.
- Example:
java
Thread.sleep(1000); // sleeps for 1 second
- Note: It throws
InterruptedException
and does not require synchronization.
2. wait() Method
- Usage:
object.wait()
- Purpose: Causes the current thread to wait until another thread calls
notify()
or notifyAll()
on the same object. - Requirements:
- Must be called within a
synchronized
block or method. - Releases the object lock during the wait.
- Example:
java
synchronized(obj) {
while (!condition) {
obj.wait();
}
}
3. notify() Method
- Usage:
object.notify()
- Purpose: Wakes up one thread that is waiting on the object's monitor.
- Note: The awakened thread cannot proceed until it re-acquires the lock.
- Usage Tip: Suitable when only one thread needs to be resumed.
4. notifyAll() Method
- Usage:
object.notifyAll()
- Purpose: Wakes up all threads waiting on the object's monitor.
- Use Case: When multiple waiting threads may proceed depending on shared conditions.
Example Using wait(), notifyAll()
java
class SharedResource {
boolean flag = false;
synchronized void setFlagTrue() {
flag = true;
notifyAll(); // Notify all waiting threads
}
synchronized void waitForFlag() throws InterruptedException {
while (!flag) {
wait(); // Wait until flag becomes true
}
System.out.println("Flag is now true!");
}
}
public class WaitNotifyExample {
public static void main(String[] args) {
SharedResource sharedResource = new SharedResource();
Thread thread1 = new Thread(() -> {
try {
sharedResource.waitForFlag();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(() -> {
// Do some work...
sharedResource.setFlagTrue();
});
thread1.start();
thread2.start();
}
}
Summary
- sleep() pauses a thread without releasing locks.
- wait() pauses a thread and releases the lock until notified.
- notify() resumes one waiting thread.
- notifyAll() resumes all waiting threads.
These methods are fundamental for effective thread coordination and should be used with care to avoid deadlocks and race conditions.