• Post Reply Bookmark Topic Watch Topic
  • New Topic

Printing numbers in sequence through threads.  RSS feed

 
Siddharth Bhargava
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a question or rather an exercise.

You have two threads, one is printing odd numbers and one is printing even number continuously. Manage them in such a way that they print numbers in sequence.

I understand that this could be done in many ways for e.g. through Semaphore, explicit locks, etc.

I have prepared its solution through wait()/notify()/notifyAll() but its not working. Following is the code:

Assumptions:
1) I am limiting the numbers to 15.
2) Also I am storing the numbers in a List and printing it at the end.
3) I am taking counter as a shared variable.









I have broken my head on this code for several days but couldn't solve this . Please do help me and do let me know what's wrong in this code which I have written. I am having nightmares. Everyday I try to solve this problem and bang my head for several hours in this but to of avail and everyday I feel disappointed. This code would help me in clarifying my concept of wait()/notify()/notifyAll().

Thanks,
Sid.

 
Amar Saikia
Ranch Hand
Posts: 43
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because the variable "oddTurn" is an instance variable to both classes Even and Odd. As both the classes need to communicate with one another to know whose turn it is, there has to be something which is shared. i.e. changes in one class need to be visible to the other class.

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!