What is the difference TimeUnit.SECONDS.sleep(1); from this.wait(1000) ?

  • 2
    For example, the fact that sleep is waiting for the dead, and the wait can end from notify() - LEQADA

1 answer 1

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.

  • 3
    wait inferior monitor, which allows two or more threads to "be" inside synchonized on one monitor. - Temka is also