• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Explain me this output (notify)

 
Shivit Agarwal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Henry Wong
author
Marshal
Pie
Posts: 21008
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Shivit Agarwal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@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
Posts: 128
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic