Difference between wait() and sleep()

前端 未结 30 3653
無奈伤痛
無奈伤痛 2020-11-22 00:24

What is the difference between a wait() and sleep() in Threads?

Is my understanding that a wait()-ing Thread is still in runni

30条回答
  •  孤城傲影
    2020-11-22 00:48

    Here, I have listed few important differences between wait() and sleep() methods.
    PS: Also click on the links to see library code (internal working, just play around a bit for better understanding).

    wait()

    1. wait() method releases the lock.
    2. wait() is the method of Object class.
    3. wait() is the non-static method - public final void wait() throws InterruptedException { //...}
    4. wait() should be notified by notify() or notifyAll() methods.
    5. wait() method needs to be called from a loop in order to deal with false alarm.

    6. wait() method must be called from synchronized context (i.e. synchronized method or block), otherwise it will throw IllegalMonitorStateException

    sleep()

    1. sleep() method doesn't release the lock.
    2. sleep() is the method of java.lang.Thread class.
    3. sleep() is the static method - public static void sleep(long millis, int nanos) throws InterruptedException { //... }
    4. after the specified amount of time, sleep() is completed.
    5. sleep() better not to call from loop(i.e. see code below).
    6. sleep() may be called from anywhere. there is no specific requirement.

    Ref: Difference between Wait and Sleep

    Code snippet for calling wait and sleep method

    synchronized(monitor){
        while(condition == true){ 
            monitor.wait()  //releases monitor lock
        }
    
        Thread.sleep(100); //puts current thread on Sleep    
    }
    

提交回复
热议问题