What's the difference between sleep and wait?



  • Different TimeUnit.SECONDS.sleep(1); from this.wait(1000)?



  • wait Could be "built" by another flow using notifysleep No way. Same. wait (sighs)notifyshould be synchronized block.

    Object obj = ...;
    synchronized (obj) {
        obj.wait();
    } 
    

    To date, current (exhaustive) flow is expected waits and releasesAnother flow can do

    synchronized (obj) { obj.notify(); }
    

    (laughs) objand the first flow will wake up. You might as well call. notifyAllIf 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 Total synchronized block).

    Another difference is that wait Called Objectwhile sleep Called Thread

    If you sum it up, use it. sleep() for time-syncronization and wait() for multi-thread-synchronization.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2