umesh agrawal


{ City } gurgaon
< Country > india
* Profession * senior software engineer
User No # 118607
Total Questions Posted # 0
Total Answers Posted # 1

Total Answers Posted for My Questions # 0
Total Views for My Questions # 0

Users Marked my Answers as Correct # 0
Users Marked my Answers as Wrong # 0
Questions / { umesh agrawal }
Questions Answers Category Views Company eMail




Answers / { umesh agrawal }

Question { Global Logic, 1623 }

write a code,
we have two thread, one is printing even no and other print the odd no.


Answer

public class EvenOdd {
public static void main(String[] args) {
final Printer printer = new Printer();
new Thread(new Runnable() {
@Override
public void run() {
int i = 1;
while (i < 100) {
printer.printOdd(i);
i = i + 2;
}
}
}).start();

new Thread(new Runnable() {
@Override
public void run() {
int i = 2;
while (i < 100) {
printer.printEven(i);
i = i + 2;
}
}
}).start();
}

static class Printer {
boolean isOdd = true;

synchronized public void printOdd(int number) {
while (!isOdd) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(number + " ");
isOdd = false;
notify();
}

synchronized public void printEven(int number) {
while (isOdd) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(number + " ");
isOdd = true;
notify();
}
}
}

Is This Answer Correct ?    0 Yes 0 No