What's the difference between sleep and wait?
-
Different
TimeUnit.SECONDS.sleep(1);
fromthis.wait(1000)
?
-
wait
Could be "built" by another flow usingnotify
♪sleep
No way. Same.wait
(sighs)notify
should besynchronized
block.Object obj = ...; synchronized (obj) { obj.wait(); }
To date, current (exhaustive) flow is expected
waits
andreleases
Another flow can dosynchronized (obj) { obj.notify(); }
(laughs)
obj
and the first flow will wake up. You might as well call.notifyAll
If more than one flow is expected, it will wake them all. However, only one of the flows will be able to capture the monitor (i.e.)wait
Totalsynchronized
block).Another difference is that
wait
CalledObject
whilesleep
CalledThread
♪If you sum it up, use it.
sleep()
for time-syncronization andwait()
for multi-thread-synchronization.