-1

I am getting an illegal monitor exception. I googled it but nothing clarifies what i am doing wrong.

From this normalclass I create an object for other class and give the object to thread and synchronize the thread. Why am I getting this exception?

/* synchronize the thread object a */
/* here iam calling wait on thread as it need to complete run */     

public class Normalclass 
{
    public static void main(String[] args)
    {
        NormalThread k = new NormalThread();
        Thread a =new Thread(k);
        a.setName("test");
        a.start();

        synchronized(a){
          try{
            a.wait();
          } catch(InterruptedException e){
            System.out.println("exception");
          }
        }
    }
}

public class NormalThread implements Runnable
{
    public void run() 
    {
        for(int i=0;i<=100;i++)
        {
            System.out.println(i);
        }
        notify();
    }
}
/* here iam notifying after the run for loop completed*/      
//  Iam getting illegal monitor exception
Mat
  • 202,337
  • 40
  • 393
  • 406
  • Rather than Googling, the **first** thing you should do is to find and read (carefully!) the javadocs for the exception (`IllegalMonitorStateException`) and the methods (`java.lang.Object::wait()` and `java.lang.Object::notify()`). But the linked Q&A explains the problem. – Stephen C Jan 03 '19 at 12:56

1 Answers1

1

In your example notify() is called on NormalThread k object while wait() is called on Thread a object. You should call these methods on the same object for the signal to propagate.

You could fix your by grabbing the monitor for k to avoid the exception by using:

synchronized(this) {
    notify();
}

but frankly the example makes little sense. Normally what you try to accomplish is done with Thread.join(). As per the method javadoc:

Waits for this thread to die.

Thread a = new Thread(k);
a.start();
a.join();
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111