The below code doesn't execute even after notifying the current thread (using this).
public synchronized void test() {
String str = new String();
try {
System.out.println("Test1");
this.wait();
this.notifyAll();
System.out.println("Test2");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Inside exception");
e.printStackTrace();
}
}
I get only Test1 as output on the console.
In, the second case I get the exception if I call the wait method on string object. The reason is because the string class object str doesn't hold lock on current object. But I wonder what does str.wait() actually means ?
public synchronized void test() {
String str = "ABC";
try {
System.out.println("Test1");
str.wait();
str.notifyAll();
System.out.println("Test2");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Ins");
e.printStackTrace();
}
}
Console Output:
> Test1
java.lang.IllegalMonitorStateException
Not sure what you expected from that code:
wait does what it says: it waits, so notifyAll is never calledwait on an object without holding the monitor of that object first. So you would need to be in a synchronized(str) block to avoid the exception. But you would still have the same issue as in 1.The main use case of wait and notify is inter-thread communication, i.e. one thread waits and another thread notifies that waiting threads can wake up. In your case the same thread is at both ends of the communication channel which does not work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With