Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Printing odd and even numbers  RSS feed

 
Hari Dhanakoti
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends,

I have a scenario to be solved.

Say thread t1 and t2 thread objects created.

Thread t1 has to print only the odd number and the t2 has to print the even number.

Can anyone give me a solution for this scenario.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hari Dhanakoti wrote:Can anyone give me a solution for this scenario.


Probably, but I am sure that isn't the intent of the assignment. How about you provide us with the work you have done and the problems you encountered while solving the problem. Then we can help you solve it.

Steve
 
sandeep jaiswal
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FAA Agree with Steve

Hi Hari,
Hope you have got by the time, if its yours Assigmnt.

In case its not :
Then here it is ...
---------------
public class EvenOddGenTest {

/**
* @param args
*/
public static void main(String[] args) {

NumberGenerator numGenerator = new NumberGenerator();

OddGenerator oddGen = new OddGenerator(numGenerator);
EvenGenerator evenGen = new EvenGenerator(numGenerator);

oddGen.start();
evenGen.start();

}

}
------------------

public class OddGenerator extends Thread {

public NumberGenerator numGen;

public OddGenerator(NumberGenerator numberGen) {
this.numGen = numberGen;
}

public void run() {
int i = 1;
while (i <= 9) {

numGen.printOdd(i);
i = i + 2;
}
}

}

----

public class EvenGenerator extends Thread {

public NumberGenerator numGen;

public EvenGenerator(NumberGenerator numberGen) {
this.numGen = numberGen;
}

public void run() {
int i = 2;
while (i <= 10) {
numGen.printEven(i);
i = i + 2;
}
}
}
------


public class NumberGenerator {

boolean oddPrinted = false;

public synchronized void printOdd(int number) {

while (oddPrinted == true) {
try {
wait();

} catch (InterruptedException e) {

}
}

System.out.println("NumberGenerator.printOdd() " + number);
oddPrinted = true;
notifyAll();

}

public synchronized void printEven(int number) {
while (oddPrinted == false) {
try {
wait();

} catch (InterruptedException e) {

}
}

oddPrinted = false;
System.out.println("NumberGenerator.printEven() " + number);
notifyAll();
}
}

--------
Enjoy....
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!