• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem in code : wait() and notify() of Thread  RSS feed

 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Details of code :

A Messenger (extends Thread) will update the value of an Integer M using a for loop. After each iteration it will wait() on M. Then, an Announcer (extends Thread) will simply
print this number and notify() . The messenger should generate numbers 1 to 10 and the Announcer should read them. And the program below throws an exception :




CODE HANGS WITH THIS OUTPUT :

 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're synchronizing on m, and then changing m within the synchronization block. When you call m.notify(), you're not synchronized on the right object.

Wouldn't synchronized(this) make more sense?

Edit, no, sorry, it wouldn't. But you need to be synchronizing on a fixed object.
 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:...you're not synchronized on the right object...
But you need to be synchronizing on a fixed object.


I want to synchronize on Integer ID. That is the fixed object. I hope there is no problem in my concepts.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!