Labels

Sunday, March 1, 2009

Object.wait() vs. Thread.sleep()

Object.wait() vs. Thread.sleep()

Thread.sleep(sometime) cause the current thread into the "Not Runnable" state for some amount of time. If another thread calls t.interrupt() it will wake up the sleeping thread. Since the Thread.sleep(sometime) is a static method and so, it will render the current thread. A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone.

object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait method is called on an object, not a thread; we call this object the "lock object." Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.