programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Printing odd and even numbers

Hari Dhanakoti
Ranch Hand
Posts: 74
Hi friends,

I have a scenario to be solved.

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