• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 :

 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic