java - notify giving IllegalMonitorStateException -


i have poor knowledge on multithreading.

i expecting below program run perfectly, not working , produces below exception.

exception in thread "thread-1" java.lang.illegalmonitorstateexception     @ java.lang.object.notify(native method)     @ com.onmobile.client.d.calld(deadlock.java:76)     @ com.onmobile.client.b.run(deadlock.java:50)     @ java.lang.thread.run(unknown source) 

java file

public class deadlock {     c c = new c();     d d = new d();      public static void main(string[] args) {             new deadlock();     }      public deadlock() {         a = new a(d,c);         b b = new b(d,c);          thread t1 = new thread(a);         thread t2 = new thread(b);          t1.start();         t2.start();     } }  class implements runnable{     d dobj;     c cobj;      a(d obj, c obj1){         this.dobj = obj;         this.cobj = obj1;     }     @override     public void run() {         cobj.callc(dobj);     } }    class b implements runnable{     d dobj;     c cobj;      b(d obj, c obj1){         this.dobj = obj;         this.cobj = obj1;     }     @override     public void run() {         dobj.calld(cobj);     } }   class c{     public synchronized void callc(d dobj){         try {             this.wait();         } catch (interruptedexception e) {             e.printstacktrace();         }         dobj.calld1();     }     public synchronized void callc1(){     }    }  class d{     public synchronized void calld(c cobj){         try {             thread.sleep(1000);         } catch (interruptedexception e) {             e.printstacktrace();         }                cobj.callc1();         cobj.notify();     }      public synchronized void calld1(){     }    } 

i thought inside callc() method, object of class c ie cobj goes in waiting state , meanwhile control go calld() method , there invokes cobj.notify(); so, awake waiting threads waiting on object cobj.

but giving me exception. think solution problem can : java: illegalmonitorstateexception on notify()

but not understanding correctly.

please guide me going wrong.

if want notify or wait on object, thread must own monitor of object act on.

public synchronized void calld(c cobj){     try {         thread.sleep(1000);     } catch (interruptedexception e) {         e.printstacktrace();     }            cobj.callc1();     cobj.notify(); } 

in code section synchronize on instance of class d, synchronized methods obtain monitor of object "live" on. able use cobj.notify() have obtain monitor of cobj instance, e.g. doing

synchronized(cobj) {    cobj.notify(); } 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -