Middle
What is the difference between the work of the wait() method with a parameter and without a parameter?
sobes.tech AI
Answer from AI
The wait() method with a parameter specifies the maximum waiting time in milliseconds. After this time, the thread automatically wakes up, even if the condition has not been met and the notify() or notifyAll() method has not been called.
The wait() method without a parameter waits indefinitely until notify() or notifyAll() is called on the object.
| Method | Parameters | Description |
|---|---|---|
wait() |
None | Waits until notify() or notifyAll() is called. |
wait(long m) |
m (milliseconds) | Waits up to m milliseconds or until notify()/notifyAll() is called. |
Example of using wait(long m):
synchronized (lockObject) {
while (conditionIsNotMet) {
try {
lockObject.wait(5000); // Wait up to 5 seconds
if (conditionIsNotMet) {
// Timeout expired, condition not met
System.out.println("Timeout expired.");
break; // Exit loop or take other actions
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// Handle interruption
}
}
}