Saturday, February 2, 2002 11:03 AM
In addition to what Duncan said there is one more important difference between sleep and wait. When a Thread goes to sleep it retains any monitors that it had prior to going to sleep. When a Thread calls wait it releases the monitor of the object that its waiting on. It is extremely important that you are aware of this because sleep is one of the easiest ways to create a deadlock condition in your code. The deadlock occurs because the Thread went to sleep while holding on to the monitor so other Threads that are contending for the monitor can't get it. If the Thread is asleep for a short time and releases the monitor relatively quickly after waking up you might not even notice that you have a deadlock condition in your code thus the bug can go undetected for a long time. But the problem can begin to compound itself under the following conditions:
1 - There are a lot of Threads contending for the monitor while the Thread is sleeping. So even though the Thread may be sleeping for a short period your code can suffer a serious degradation in performance because of the contention overhead.
2 - The Thread sleeps for an extend period of time.
3 - The sleep is happening in a loop that won't exit until some condition has been met but the condition changing is dependent on some other Thread gaining the monitor that the sleeping Thread is holding on to. This is the classic deadlock scenario.
Finally, here is a good Thread programming practice that you should always follow. If there is a call to wait on an object without a timeout being specified, you MUST ensure that eventually there is a call to notify or notifyAll on the same object. Failing to do what I've just said is another major case of deadlock in Java code.