My question in when we use a synchronization block, the object on which the threads have to be synchronized should be static?
For Ex: In this code threads are synchronized on static object. So all the threads have common object monitor.
If I synchronize on object info then why aren't the threads notified when the count becomes equal to 3.
import java.util.Vector;
public class WaitAndNotify_2 extends Thread{
private
String info;
static Integer monitor = new Integer(3);
static int count = 0;
static int max = 0;
public WaitAndNotify_2 (String info) {
this.info = info;
}
public void doTheJob() {
synchronized ( monitor ){
System.out.println(info + " is waiting");
count ++;
if ( count == 3 )
monitor.notifyAll();
else
try {
monitor.wait();
sleep(1000);
} catch ( Exception e ){
System.out.println(info +
": IllegalMonitorStateException");
}
System.out.println(info + " is awake!");
}
}
public void run () {
doTheJob();
}
public static void main (String args []) {
new WaitAndNotify_2("first").start();
new WaitAndNotify_2("second").start();
new WaitAndNotify_2("last").start();
}
}