import java.util.*;
import java.io.*;
import java.util.regex.*;
class ZiggyTest2 extends Thread{
String sa;
public ZiggyTest2(String sa){
this.sa = sa;
}
public void run(){
synchronized(sa){
while(!sa.equals("Done")){
try{
sa.wait();
}catch(InterruptedException is){System.out.println("IE Exception");}
}
}
System.out.println(sa);
}
}
class Test{
private static String sa = new String("Not Done");
public static void main(String[] args){
Thread t1 = new ZiggyTest2(sa);
t1.start();
synchronized(sa){
sa = new String("Done");
sa.notify();
}
}
}
When i run the above program i get the following exception:
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at Test.main(ZiggyTest2.java:35)
A couple of questions:
Why the IllegalMonitorStateException? Because Test.sa is assigned to a new String object, i was expecting the ZiggyTest2 thread to wait indefinately because sa.notify() will be called on a different lock than the one used in ZiggyTest2.
In the above example, wait() & notify() are called on the "sa" object. What is the difference in say calling notify() on its own and calling notify()/wait() using an object i.e. sa.wait() and sa.notify()?
Does it matter that in the Test class the synchronised block has the lock for the sa object and the sa object is static but in the ZiggyTest2 class, the synchronised block uses the same sa object reference but using a non static reference? Given that one is static and the other is not, will they both still be using the same lock?