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



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

Answer / umeshag89

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

Post New Answer

More Core Java Interview Questions

Explain about map interface in java?

0 Answers  


Hi Friends.. can any one provide the real time example for methodoverloading and methodoverriding .........

2 Answers   Honeywell,


How do you invoke a method?

0 Answers  


What is thread safe java?

0 Answers  


What is the function of character?

0 Answers  






What is the difference between a public and a non-public class?

2 Answers  


What is the purpose of void?

0 Answers  


What is meant by binding in rmi?

0 Answers  


A abstract class extending an abstract class.Super class has both abstract and non-abstract methods.How can we implement abstract and non-abstract mehtods? Explain with snippet

3 Answers  


What are actual parameters?

0 Answers  


What is the main functionality of Prepared Statement?

4 Answers  


Explain about automatic type conversion in java?

0 Answers  


Categories