What is the difference TimeUnit.SECONDS.sleep(1); from this.wait(1000) ?
|
1 answer
wait can be "awakened" by another thread using notify , sleep cannot. Similarly wait (and notify ) must be in a synchronized block.
Object obj = ...; synchronized (obj) { obj.wait(); } While the current (running) thread is waiting for waits and releases , another thread can make
synchronized (obj) { obj.notify(); } (on the same obj ) and the first thread will wake up. You can also call notifyAll , if more than one thread is waiting, it will wake them all up. However, only one of the threads will be able to capture the monitor (since the wait in the synchronized block).
Another difference is that wait is called on Object , while sleep is called on Thread .
To summarize, use sleep() for time-syncronization and wait() for multi-thread-synchronization.
- 3wait inferior monitor, which allows two or more threads to "be" inside synchonized on one monitor. - Temka is also
|
sleepis waiting for the dead, and thewaitcan end fromnotify()- LEQADA