Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • 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 ...
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
  • Piet Souris
  • Himai Minh

Printing numbers in sequence through threads.

Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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:

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().


Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

A tiny monkey bit me and I got tiny ads:
Free, earth friendly heat - from the CodeRanch trailboss
    Bookmark Topic Watch Topic
  • New Topic