What is the difference between `wait()` and `sleep()`?
The main differences between wait()
and sleep()
are in their purpose, behavior, and usage:
wait()
:- Used in synchronized blocks or methods to release the lock and put the current thread into the waiting state.
- It requires the thread to hold a lock (or monitor) before calling.
- The thread remains in the waiting state until notified (via
notify()
ornotifyAll()
). - Can throw
InterruptedException
.
sleep()
:- Used to pause the execution of the current thread for a specified amount of time.
- Does not release the lock, so other threads may not proceed while the current thread is sleeping.
- Does not require synchronization and can be called from any context.
- Can throw
InterruptedException
.
In summary, wait()
is used for inter-thread communication within synchronized blocks, while sleep()
is for pausing the thread for a specified duration without releasing the lock.