This exception is thrown when you try to call
wait()/notify()/notifyAll() any of these methods for an Object from a
point in your program where u are NOT having a lock on that object.(i.e.
u r not executing any synchronized block/method of that object and
still trying to call wait()/notify()/notifyAll())
wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.
wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.
- class IllegalMonitorStateExample
- {
- public static void main(String a[])
- {
- AnObject o = new AnObject();
- Thread inc = new Thread(new IncrUser(o));
- Thread dec = new Thread(new DecrUser(o));
- inc.start();
- dec.start();
- }
- }
- class IncrUser implements Runnable
- {
- AnObject a ;
- IncrUser()
- {
- }
- IncrUser(AnObject a)
- {
- this.a = a;
- }
- public void run()
- {
- while(true)
- {
- try
- {
- [B]// a.wait();[/B]
- a.incr();
- Thread.sleep(1000);
- [B] // a.notify(); //[/B]
- }
- catch(InterruptedException ie)
- {
- ie.printStackTrace();
- }
- }
- }
- }
- class DecrUser implements Runnable
- {
- AnObject a ;
- DecrUser()
- {
- }
- DecrUser(AnObject a)
- {
- this.a = a;
- }
- public void run()
- {
- while(true)
- {
- try
- {
- a.decr();
- Thread.sleep(1000);
- }
- catch(InterruptedException ie)
- {
- ie.printStackTrace();
- }
- }
- }
- }
- class AnObject{
- int myNum = 0;
- synchronized void incr() throws InterruptedException
- {
- if(myNum!=0)
- {
- System.out.println("ready to incr but muNum not zero +++++++++++++++");
- wait();
- }
- myNum++;
- print("produced : ");
- notify();
- }
- synchronized void decr() throws InterruptedException
- {
- if(myNum==0)
- {
- System.out.println("ready to decr but myNum not 1 ----------");
- wait();
- }
- myNum--;
- print("consumed : ");
- notify();
- }
- void print(String s)
- {
- System.out.println(s + " "+myNum);
- }
- }
Good Example
ReplyDelete