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

What is java dot?

0 Answers  


What is ternary operator? Give an example.

0 Answers  


How to check if a list is sorted in java?

0 Answers  


What is the meaning of course?

0 Answers  


class A { public void disp(int a,int b) { System.out.println("hai"); } } class B { public void disp(int a,int b,int c) { System.out.println("hai"); } } above program is overloading or overriding?

9 Answers   Infosys, Wipro,






why static class in java or what is use of static class in java

3 Answers   SunGard,


What is an object class?

0 Answers  


what is run time polymorphism

4 Answers  


how and when compiler knows that the Java code throws the checked Exception.

2 Answers   HSBC,


What does g mean in regex?

0 Answers  


How can you traverse a linked list in java?

0 Answers  


why we import both packages java.awt.*; and java.awt.event.*; as java.awt.*; can import all classes na. then what is the need of importing java.awt.event.*; ?

3 Answers  


Categories