Hi ,
I was trying following code
class A
{
void met(Object s)
{
synchronized(this)
{
System.out.println(Thread.currentThread()+"["+s);
System.out.println(Thread.holdsLock(this));
try
{
Thread.sleep(1000);
Thread.currentThread().wait();//...line1
}
catch (InterruptedException e)
{
}
System.out.println(s+"]");
}
}
}
class D implements Runnable
{
A ob;
String s;
D(A a,String b)
{
s=b;
ob=a;
Thread t=new Thread(this);
t.start();
}
public void run()
{
ob.met(s);
}
public static void main(String[] args)
{
A a1=new A();
D d1=new D(a1,"java");
D d2=new D(a1,"synchronized");
}
}
In this code there are 2 objects d1 & d2 are created which try to access the synchronized method met() on the same object a1.On line 1 i have called wait() method beacuse of which current thread leaves the monitor & 2nd thread(of obejct d2) starts executing met().
I dont understand why is it giving "IllegalMonitorStateException" when 2nd thread reaches wait() method although "System.out.println(Thread.holdsLock(this));" returns true for both the threads.
Also one thing i observed is if instead of "Thread.currentThread().wait();" if we call only "wait()" then it doesnt throw any exception.
Please help me in this.