Monday, June 6, 2016

Difference between sleep and wait in java ?

Sleep and wait () method

sleep () is a method , which is used to hold the process for a particular time or How much time you wanted to hold. 

wait () method goes to waiting stage and it wont come back to normal until notify() or notifyAll() method should be called. 

Important points about sleep() method

1. Sleep is a static method on Thread class. 

2. It will makes your current thread into Not Runnable state for the specified amount of time.      
    Thread keeps the lock, during this time. 

3. It will be waked by interrupt or time expires.

4. It throws interrupted exception if another thread interrupts a sleeping thread.


Important points about wait() method

1. wait is an object class method.

2. It will makes your current thread into Not Runnable state. 

3. Remember, wait is called on an object not on thread. 

4. wait() should be used inside synchronized block or synchronized method. 

5. It will release the lock and gives the chance to others. 

6. It will be awake by calling on notify() or notifyAll() methods.

No comments:

Post a Comment