| Author |
Explain me this output (notify)
|
Shivit Agarwal
Ranch Hand
Joined: Feb 28, 2008
Posts: 82
|
|
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.
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
My second question is what happens when a notify() is encountered before a wait() statement as in the program below ??
If a notify() is called, when there are no threads waiting on the monitor, the notification is lost. Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Shivit Agarwal
Ranch Hand
Joined: Feb 28, 2008
Posts: 82
|
|
@Henry Thanks mate. But can yoyu tell me the use of notify(). In the above code what notify is doing I cannot see any purpose behind above ??
|
 |
Keith Flo
Ranch Hand
Joined: Nov 29, 2005
Posts: 128
|
|
Shivit, 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. hope this helps.
|
kf
SCJP 5.0 (preparing for SCWCD)
|
 |
 |
|
|
subject: Explain me this output (notify)
|
|
|