sleep()- is used to pause the process for a specified amount of timewait()- moves the thread into waiting state and it won’t come back automatically until we call thenotify()ornotifyAll()
Behavior with Locks
sleep()- doesn’t releases the lock or monitor while waitingwait()- releases the lock or monitor
synchronized(LOCK) {
Thread.sleep(1000); // LOCK is held
}
synchronized(LOCK) {
LOCK.wait(); // LOCK is not held
}
Summary
|
sleep() |
wait() | |
|---|---|---|
|
method called on |
Call on a Thread; always currently executing thread |
Call on an object; current thread must synchronize on the lock object |
|
synchronized |
when synchronized multiple threads wait for sleep over of sleeping thread |
when synchronized multiple threads access same Object one by one |
|
lock duration |
keep lock for at least t times if timeout specified or somebody interrupt |
release the lock for other objects to have chance to execute |
|
wake up condition |
until at least time expire or call interrupt() |
until call notify(), notifyAll() from object |
|
usage |
for multi-thread-synchronization |
for time-synchronization |