| Author |
IllegalMonitorStateException
|
venkatesh pendharkar
Ranch Hand
Joined: Apr 29, 2006
Posts: 104
|
|
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.
|
 |
Vlado Zajac
Ranch Hand
Joined: Aug 03, 2004
Posts: 244
|
|
You should use "wait();" instead of "Thread.currentThread().wait();" to wait on the A object (a1). wait() is a method of Object not Thread and it always causes current thread to stop. The reason for exception is that this!=Thread.currentThread() (inside met method). The code holds lock on this but tries to wait on Thread.currentThread().
|
 |
venkatesh pendharkar
Ranch Hand
Joined: Apr 29, 2006
Posts: 104
|
|
ok so you mean that wait() should be called on current object & not on current thread...& Thread.currentThread() doent return refference of current object;it returns ref.for current thread. Am i correct? Anyways thanks a lot for helping me out in this
|
 |
 |
|
|
subject: IllegalMonitorStateException
|
|
|