I am trying to execute 2 threads in interleaved manner. One is printing odd numbers and other is printing even numbers to the console (<=100). I want the output to be : 1 2 3 4 5 6 7 8 9 10 .... and so on. i.e they should execute one after another in order.
Here is the code for this:
class Monitor{
boolean flag = false;
}
class OddNumberPrinter implements Runnable{
Monitor monitor;
OddNumberPrinter(Monitor monitor){
this.monitor = monitor;
}
@Override
public void run() {
for (int i = 1; i<100; i+=2){
synchronized (monitor){
while(monitor.flag == true){
try {
wait();
} catch (Exception e) {}
}
System.out.print(i+" ");
monitor.flag = true;
notify();
}
}
}
}
class EvenNumberPrinter implements Runnable{
Monitor monitor;
EvenNumberPrinter(Monitor monitor){
this.monitor = monitor;
}
@Override
public void run() {
for (int i = 2; i<101; i+=2){
synchronized (monitor){
while (monitor.flag == false){
try {
wait();
} catch (Exception e) {}
}
System.out.print(i + " ");
monitor.flag = false;
notify();
}
}
}
}
public class InterleavingThreads {
public static void main(String[] args) throws InterruptedException {
Monitor monitor = new Monitor();
Thread t1 = new Thread(new OddNumberPrinter(monitor));
Thread t2 = new Thread(new EvenNumberPrinter(monitor));
t1.start();
t2.start();
}
}
When I standalone use wait() and notify(), it throws exception, but using monitor.wait() and monitor.notify() gives the correct output. Please explain the difference in these two.