• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Printing Odd Even via Thread  RSS feed

 
Ranch Hand
Posts: 227
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


How to restrict the printing of the numbers till 10. As of now it prints upto 11.
Sample Output:-



 
Rancher
Posts: 3337
33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is another problem with the logic.  Sometimes the code hangs after printing: Even - 10
There must be a way for wait to be called without a notify.
 
Master Rancher
Posts: 3002
105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To eliminate printing "Odd - 11" simply change the printinhg line in the "Odd" section to:

However, this does not solve the problem that Norm Radder mentions. It is possible that the "Odd" Thread sends an 'object.notify' just before the "Even" Thread issues 'object.wait'. In that case the "Even" Thread will wait forever for a notify that will never come. How?

Suppose that i = 10, and that we are in the Even thread. It puts i to 11, then issues 'object.wait'.
Now look at the Odd thread. Suppose that when Even does the 'object.wait', that Odd has just gone past line 29. It will jump to the while line and evaluates if i <= 10. Since i = 11, Odd finishes and so will never issue 'object.notify'. In that case the Even thread waits for a notify that will never come.
If, on the other hand, Odd is just before the if-condition, it finds that i == 11 (as just set from the Even thread), and so it issues the 'object.notify', releasing the Even thread and all is fine.

Complicated? Yes.

But why should you use the wait and notify mechanism in the first place? This should be simple enough:

But does that not leave the possibility of a race condition? Suppose we're in Even, i = 6, and it has just evaluated

Is it possible that at that very moment Odd will increase i to 7? If so, what will happen? And if not, why not?

Lastly, what do you think about this simplified version:
 
Santosh Kumar Nayak
Ranch Hand
Posts: 227
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
   
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!