Thursday, 31 December 2015

6 Difference between wait() and sleep() method in Java

Though both wait() and sleep() method are used to pause the running thread, here are some important difference between them:

1) The wait() method must be called from the synchronized context (can be a synchronized block or method) but sleep() method can be called from within our with-out synchronized block.

2) When you call the wait() method, the Thread will release the lock it was holding but Thread keep holding the lock even after calling the sleep() method.

3) The wait() method is defined in the java.lang.Object class but the sleep() method is defined in java.lang.Thread class.

4) The thread which have called wait() can be woken up by other threads by calling notify() and notifyAll() method, but sleeping thread cannot be woken by another thread until the time out, but another thread can always interrupt the sleeping thread.

5) The most important difference between wait() and sleep() method is that you call wait() on objects i.e. monitor but sleep() method is called on Thread.

6)  After calling wait() method, the thread goes to WAITING state but after calling the sleep() method the thread goes to TIMED_WAITING state.

This was the difference between wait and sleep method in Java. If you think that I have missed out any important difference then please suggest and I'll add into this list. Thank you.

No comments:

Post a Comment