java - IllegalMonitorStateException while calling wait() in run() -
i have created java thread , passed stack reference it's constructor, initialize thread stack reference. in run method have created synchronized block stack object, moment calling wait in run inside synchronized block , getting illegalmonitorstateexception.
thread class :
public class producer extends thread { stack<string> stack=null; public producer(stack<string> stack) { this.stack=stack; } @override public void run() { synchronized (stack) { if(stack.isempty()){ try { wait(); } catch (interruptedexception e) { e.printstacktrace(); } } } } }
main class:
public class mainclass { public static void main(string[] args) { stack<string> stack=new stack<string>(); producer p=new producer(stack); p.start(); } }
output :
exception in thread "thread-0" java.lang.illegalmonitorstateexception @ java.lang.object.wait(native method) @ java.lang.object.wait(object.java:485) @ demo.producer.run(producer.java:20)
for wait() (or notify()) work, must call on same object. have same
synchronized (stack) { if(stack.isempty()){ try { this.wait(); } catch (interruptedexception e) { e.printstacktrace(); } } }
instead should do
synchronized (stack) { if(stack.isempty()){ try { stack.wait(); // wait on same object synchronized. } catch (interruptedexception e) { e.printstacktrace(); } } }
note: wait can wake spuriously have in loop or method return prematurely.
synchronized (stack) { while (stack.isempty()){ try { stack.wait(); } catch (interruptedexception e) { e.printstacktrace(); } } }
Comments
Post a Comment