when I say wait(2000) so that means it will wait for 2 sec....right? So my question is then what is the use of notifying a thread since after 2 sec it will automatically enter into the runnable state?
Or is it we use notify in case when we dont specify the time frame for the wait method. Please confirm......
And one more querry Do wait methods take lock along with them when they enter in the waiting state.?
Joined: Aug 28, 2005
Hi, What if you have called wait as : wait(200000) Now this will make the thread wait for 200 sec or more...and now if you want to wake the thread just after 5 sec...you must have some mechanism to do it, Notify helps to do so.
For your second query you are suggested to read api of wait method in object class, you will get the answer.
Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
Joined: Aug 17, 2005
The wait method releases the lock. Therefore for the thread that calls wait does not become runnable until it obtains the lock again. It will have to be notified by some other thread.
When a waiting thread is timed out/notified/interrupted it does not go the runnable state - but is in the waiting for lock state. A waiting thread can come out of wait before its timeout if there is a notify/notifyAll call - do read the api for wait calls.
When a thread calls the wait without specifying anytime then the only way for it to get back to waiting for lock state is either to be notified or interrupted.
Also note that notifying alone doesnot release the lock. The thread notifying has to complete its synchronized code. i.e, after notifying if the notifying thread performs some other action within the same synchronized context then the lock will not be released. Only aferwardsis the lock released by the thread that notifies other waiting threads. [ October 09, 2005: Message edited by: sankar velamuri ]
Joined: Jul 01, 2005
One more thing is it always necessary to call a notify method to bring a waiting thread back to runnable state, or is it only necessary with the case of wait with no time frame defined.
Joined: Aug 28, 2005
To a great extent you are right patrick. it only necessary with the case of wait with no time frame defined. But I think that if you dont at all specify the notify then the compiler itself calls the notify on the thread after some time..(I am not sure of it).
I'll confirm it very soon, By that time if anyone else could throw some light then it would be great.
This is very simple because wait have two forms i.e., wait(); - for this we must have to call notify where as in the second form we needn't to call notify because it works timeslice . wait(1000)- it will wait for 10 sec & after that it will be automatically started.
Note : we can call the notify in case of wait(time) also.