I tried the code below. I took this piece of code from some other post which is correct as per the author. But when I try running, it doesn't give me the exact result.
This is mainly to print even and odd values in sequence.
public class PrintEvenOddTester {
public static void main(String ... args){
Printer print = new Printer(false);
Thread t1 = new Thread(new TaskEvenOdd(print));
Thread t2 = new Thread(new TaskEvenOdd(print));
t1.start();
t2.start();
}
}
class TaskEvenOdd implements Runnable {
int number=1;
Printer print;
TaskEvenOdd(Printer print){
this.print = print;
}
@Override
public void run() {
System.out.println("Run method");
while(number<10){
if(number%2 == 0){
System.out.println("Number is :"+ number);
print.printEven(number);
number+=2;
}
else {
System.out.println("Number is :"+ number);
print.printOdd(number);
number+=2;
}
}
}
}
class Printer {
boolean isOdd;
Printer(boolean isOdd){
this.isOdd = isOdd;
}
synchronized void printEven(int number) {
while(isOdd){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Even:"+number);
isOdd = true;
notifyAll();
}
synchronized void printOdd(int number) {
while(!isOdd){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Odd:"+number);
isOdd = false;
notifyAll();
}
}
Can someone help me in fixing this?
EDIT Expected result: Odd:1 Even:2 Odd:3 Even:4 Odd:5 Even:6 Odd:7 Even:8 Odd:9
Here is the working code to print odd even no alternatively using wait and notify mechanism. I have restrict the limit of numbers to print 1 to 50.
I have done it this way, while printing using two threads we cannot predict the sequence which thread
would get executed first so to overcome this situation we have to synchronize the shared resource,in
my case the print function which two threads are trying to access.
Class to print odd Even number
Driver Program
Please use the following code to print odd and even number in a proper order along with desired messages.