What is the difference when using standalone wait() method and using any instance of a class ( obj.wait() )

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...

Read More »

By: StackOverFlow - Monday, 3 December

Related Posts