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
How many bits is a float?
How do you sort a string in alphabetical order in java?
Explain about java sdk?
What is json parser in java?
What restrictions are placed on method overriding?
What happens if I remove static from main method?
Mention a package that is used for linked list class in java.
Why is it important to initialize a variable?
What is a boolean structure?
Can we force the garbage collection to run?
Differences between traditional programming language and object oriented programming language?
What does regex mean?
Can you call one constructor from another if a class has multiple constructors?
How do you define a parameter?
hi am an engineering student and my next plan is for ms in either in us or australia i got my passport but i dont know anything bout visa can u give brief idea 1)How to get prepared for visa and 2)How to apply for top universities and 3)How to pay the fee and so on These all are basic questions plz give me a clear idea