• Post Reply Bookmark Topic Watch Topic
  • New Topic

Printing Odd Even via Thread  RSS feed

 
Santosh Kumar Nayak
Ranch Hand
Posts: 193
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:-



 
Norm Radder
Ranch Foreman
Posts: 2240
28
  • 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.
 
Piet Souris
Rancher
Posts: 1984
67
  • 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: 193
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
    
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!