write a code,
we have two thread, one is printing even no and other print the odd no.
Answer Posted / 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 View All Answers
What is difference between fileinputstream and filereader in java?
Can you make a constructor final in Java?
What is the difference between serializable and externalizable interface?
Can we declare the static variables and methods in an abstract class?
What is an abstract class and what is it’s purpose?
How do you declare a string variable?
What is an immutable object?
Why is serialization required?
What is the use of a conditional inclusion statement in Java ?
What are access specifiers in java ?
What restrictions are placed on method overloading?
What is exception in java?
What are the string methods in java?
What is __ init __ functions?
What is api data?