Hi,
Thread.sleep()is used to make the
thread sleep for a specified time. This gives other threads CPU time.
wait()method is used to relinquish a object lock and then the thread enters the wait state.When a thread gets invokes a synchronized method it obtains that object's lock. If it now wants to give other threads the objects lock it will invoke the wait method. This will take the current thread to wait queue i.e. the thread stop executing. Now other threads which are competing for the object's lock will get an opportunity. The previous thread which is now in wait state will get an opportunity to continue executing from the point where it left off(i.e.where it called wait) only when any other threads call notify/notifyall() method. Of course the previous thread has to compete with other threads to get hold of lock. The wait,notify and notifyall methods can only be used within an synchronized block or method.
In short u use sleep to give other threads an opportunity to get CPU timw whereas wait is used when other threads need to get hold of an objects lock.
Originally posted by Pho Tek:
When do you decide to use Thread.sleep(long)
or Object.wait(long) ? Any gotchas that
I should watch out for ?
Thanks
Pho