what could be diffrent scenarios to use wait() and sleep() methods, it sounds the purpose of these methods is similar. I know wait() is from Object Class and sleep() from Thread, but the purpose sounds similar.PLease clarify me ???
wait() causes a thread to give up its lock on the object on which wait is called. The thread then sits in a blocked/waiting state until the object being waited on receives a notify message from another thread. Then the waiting thread wakes up and attempts to continue executing, having regained the lock on the object. wait() must be called from a context that is synchronized on the object in question.
sleep() causes a thread to pause its execution for a specified time, taking all its locks with it. It will wake up after the time expires, without being notified. sleep() can be called from a synchronized or non-synchronized context.
Basically, wait is used when a thread is "waiting" for a certain condition to be met, at which time it will presumably be "notified" so it can resume. (See the notify and notifyAll methods in Object.) This is often used with resources protected by a lock (synchronized code). While waiting, the thread releases its lock on those resources so that other threads can use them.
On the other hand, sleep is basically a pause in the thread's execution. Locks are not released while sleeping, although the CPU is freed up to do other things.
Usually you use wait and notify methods when at least two threads are sharing a common resource. It's typical in a consumer/producer relationship.
Imagine, for example, a thread (producer) which is pushing objects into a stack, and concurrently another thread (consumer) which is popping them out.
If the producer realizes that the stack is full you could make the producer thread to "wait" until the consumer has has popped out all the items. Likewise, if the consumer pops all the items out of the stack, then the stack is empty, and the consumer could notify the producer to stop waiting and continue to push items into the stack.
I wrote this sample code, but I do no have a Java compiler here, so I apologize in case it does not compile. I hope it helps at least for illustrative purposes.
[ April 26, 2005: Message edited by: Edwin Dalorzo ] [ April 26, 2005: Message edited by: Edwin Dalorzo ]
Joined: Apr 10, 2005
Here's a debugged version of Edwin's nifty example: