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 java dot?
What is ternary operator? Give an example.
How to check if a list is sorted in java?
What is the meaning of course?
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?
why static class in java or what is use of static class in java
What is an object class?
what is run time polymorphism
how and when compiler knows that the Java code throws the checked Exception.
What does g mean in regex?
How can you traverse a linked list in java?
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.*; ?