Print Alternatively numbers from two different thread using java (java Interview Question)
- manbodh ratre
- Jul 21, 2024
- 1 min read
Question is to execute one task from one thread and then wait and notify another thread to work
public static void main(String[] agrs){
Printer p = new Printer();
Runnable r1 = () -> {
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0)
p.printEven(i);
}
};
Runnable r2 = () -> {
for (int i = 0; i <= 10; i++) {
if (i % 2 != 0)
p.printOdd(i);
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}class Printer {
private boolean evenTrue = true;
public synchronized void printEven(int number) {
while (!evenTrue) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.print(number + " ");
evenTrue = false;
notify();
}
public synchronized void printOdd(int number) {
while (evenTrue) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.print(number + " ");
evenTrue = true;
notify();
}
}






Comments