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 command line argument in java?

0 Answers  


What is the static field modifier?

0 Answers  


What is the use of an interface?

3 Answers  


how to create an applet

2 Answers  


What is the immediate superclass of Menu?

3 Answers  






what are the new features available in java 1.5 version?

3 Answers   Accenture, Features, Motorola,


What is a stream? what are the different types and classes of Streams?

2 Answers  


What is valid keyword in java?

0 Answers  


Is main an identifier?

0 Answers  


What is the default size of set in java?

0 Answers  


What are the methods of object class ?

0 Answers  


Write a function for palindrome and factorial and explain?

0 Answers   Honeywell, Huawei, Zomato,


Categories