Need a better understanding of Java Synchronized Object behaviour and IllegalMonitorStateException
<p>So I have a java object that executes <code>wait()</code> and then another thread executes <code>notifyAll()</code> on the same object.</p>

<p>When I initially tried this, it wouldn't work. It would throw an <code>IllegalMonitorStateException</code>.</p>

<pre><code>Thread refreshThread = new Thread(new Runnable() {

   final Object dirtyLock = new Object();

   public void run() {

      while(true)
      {     
         try
         {
            dirtyLock.wait();
         } 
         catch (InterruptedException e)
         {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }
   }
});
refreshThread.start();
</code></pre>

<p>But if i surround the <code>while(true)</code> loop with the following code, it works.</p>

<pre><code>synchronized(dirtyLock){ /* while loop */ }
</code></pre>

<p>Now I had to do this in the function that notifies this thread to awake too.</p>

<pre><code>synchronized(dirtyLock){ dirtyLock.notifyAll(); }
</code></pre>

<p>Does <code>synchronized</code> give the thread ownership of the monitor object? How can two different threads claim ownership of the same monitor?</p>

<p>p.s. the question may sound dumb to some but I just want to learn how this behaviour works instead of just blindly coding.</p>
