Hello, I didn't get the output ...Can anybody explain me ?? I have bolden the problem in output.
The code is from THE COMPLETE REFERENCE - HERBERT SCHILDT
My second question is what happens when a notify() is encountered before a wait() statement as in the program below ??
Output Producer hai Put : 0 What will be the next line Entry of Put :1 Why and how this line gets printed Consumer hai Got : 0 Entry in get:0 Put : 1 What will be the next line How many times Got : 1 Entry in get:1 Put : 2 What will be the next line How many times Got : 2 Entry in get:2 Put : 3 What will be the next line How many times Got : 3 Entry in get:3 Put : 4 What will be the next line How many times Got : 4 Entry in get:4 Put : 5 What will be the next line Entry of Put :6 How many times Got : 5 Entry in get:5 Put : 6 What will be the next line How many times Got : 6 Entry in get:6 Put : 7 What will be the next line How many times Got : 7 Entry in get:7
[HENRY: Fixed Indentation in Code] [ April 19, 2008: Message edited by: Henry Wong ]
Have the determination of mirror which never fails to reflect in spite of being broken into pieces.<br /> <br />Kiss the hands you cannot bite.<br /> <br />An Optimist is one who starts taking a bath when he accidentally falls into the water.
without trying to debug the above example ... here is how notify() works.
Notify() is a method of class object that informs one thread and one thread only (notifyAll() informs all waiting threads) that it can stop waiting and continue with program execution.
For example: thread A acquires the lock [aka 'monitor'] on object Foo which is running in thread B. Thread A calls the wait method() of the Foo instance and releases its lock. This tells Foo instance .. I'm gonna wait until you notify me that you are finished whatever it it is you are doing. Foo instance finishes and calls notify(). Thread A goes back to runnable, reaquires the lock on foo instance and will complete.
Both wait and notify must be called from a synchronized method (or block). Wait throws an InterruptedException.