title: Java synchronize block on same object in different methods
body: <p>I am trying to understand the concept of synchronized blocks in java.
  As of the documents that I have read, I understood that if we acquire
  a lock ( synchronized block using an instance variable ) then we
  cannot acquire a synchronized lock on same object in that class. But
  when I tried practically using the following snippet I found that my
  understanding is going wrong. </p>
  
  <p>I.e I am able to acquire lock
  (synchronized block on same instance variable) in two different
  methods at the same time. When the thread is started it will go to run
  method and wait indefinitely and will not come out of the synchronized
  block. At the same time if I call the stop method using the same
  thread it goes into the synchronized block and executes notify
  statement. I searched in the Java doc but I couldn't find any. </p>
  
  <p>This is the code snippet:</p>
  
  <pre><code>public class MyClass extends Thread
  {
      private Object lock = new Object(); 
      public void run()
      {
        synchronized(lock)
        {
            lock.wait()
        }
        //other code
      }
      public void stop()
      {
        synchronized(lock)
        {
            lock.notify()
        }
        //other code
      } 
  }
  </code></pre>
  
  <p>Here is the code snippet of how i am managing the MyClass thread:</p>
  
  <pre><code>public class MyClassAdmin 
  {
      MyClass _myclass;
      public MyClassAdmin()
      {
          _myclass=new MyClass();
          _myclass.start();
      }
      public void stop()
      {
      _myclass.stop();
      }
      public static void main(String args[])
      {
      MyClassAdmin _myclassAdmin=new MyClassAdmin();
      _myclassAdmin.stop();
      }
  }
  </code></pre>
  
  <p>According to my understanding when the thread is started it will acquire lock on 'lock' object (synchronized block in run method of MyClass). When i call the stop method it should wait indefinitely until the run method comes out of the synchronized block (which will never happen in this case). But when i executed, call to stop method acquired lock on the 'lock' object and notified the object which resulted in shutdown of the thread.</p>