write a code,
we have two thread, one is printing even no and other print the odd no.
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 |
What is command line argument in java?
What is the static field modifier?
What is the use of an interface?
how to create an applet
What is the immediate superclass of Menu?
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?
What is valid keyword in java?
Is main an identifier?
What is the default size of set in java?
What are the methods of object class ?
Write a function for palindrome and factorial and explain?
0 Answers Honeywell, Huawei, Zomato,