Monday, December 28, 2015

Sleep and Wait Method

Difference between sleep() and wait()

Sleep()
Wait()
     1)     Static method of Thread class
     1)     Method of Object Class
     2)     Thread keeps the lock it has acquired

synchronized(LOCK) {
    Thread.sleep(1000); // LOCK is held
}

     2)     Call to wait() releases the acquired lock

synchronized(LOCK) {
    LOCK.wait(); // LOCK is not held
}

     3)     It is called on Thread class
     3)     Wait is called on an object, not a thread
     4)     The Object need not to be in synchronized block
     4)     Before calling wait() , the object should be in synchronized , means the object should be in synchronized block.
     5)    Wake-up, when time expires or interrupt() called on the thread.
     5)   Wake-up when notify(),notifyAll() called from object
     6)     Usage : for time-synchronization               
     6)     Usage : for multi-thread communication



No comments:

Post a Comment