title: How to notify a specific thread in Java
body: <p>How I can call a particular thread in inter-thread communication?</p>
  
  <p>In the program below I have two threads <code>t1</code> and <code>t2</code>.</p>
  
  <p>When I call <code>t1.notify()</code> it raises:</p>
  
  <pre><code>Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
      at java.lang.Object.notify(Native Method)
      at Shared.methodTwo(NotifyThread.java:43)
      at Thread2.run(NotifyThread.java:77)
  Error 
  </code></pre>
  
  <hr>
  
  <pre><code>class Shared {
  
      Thread1 t1 ;
      Thread2 t2 ;
  
      void ThreadInit( Thread1 t1 , Thread2 t2 ) {
          this.t1 = t1 ;
          this.t2 = t2 ;
      }
  
      synchronized void methodOne()
      {
          Thread t = Thread.currentThread();
  
          System.out.println(t.getName()+" is relasing the lock and going to wait");
  
          try
          {
              wait();        //releases the lock of this object and waits
          }
          catch (InterruptedException e)
          {
              e.printStackTrace();
          }
  
          System.out.println(t.getName()+" got the object lock back and can continue with it's execution");
      }
  
      synchronized void methodTwo()
      {
          Thread t = Thread.currentThread();
  
          try
          {
              Thread.sleep(5000);
          }
          catch (InterruptedException e)
          {
              e.printStackTrace();
          }
  
          t1.notify();     
  
          System.out.println("A thread which is waiting for lock of this object is notified by "+t.getName());
      }
      }
  
      class Thread1 extends Thread 
      {
      Shared s ;
      Thread1( Shared s ) {
  
          this.s = s ;
      }
  
      public void run()
              {
                  s.methodOne();   //t1 calling methodOne() of 's' object
              }
  
      } 
  
      class Thread2 extends Thread {
           Shared s ;
      Thread2( Shared s ) {
  
          this.s = s ;
  
      }
  
      public void run()
              {
                  s.methodTwo();   //t1 calling methodOne() of 's' object
              }
  
  
      }
      public class NotifyThread 
      {
      public static void main(String[] args)
      {
          final Shared s = new Shared();
  
          Thread1 t1 = new Thread1(s) ;
          Thread2 t2 = new Thread2(s) ;
  
          s.ThreadInit(t1,t2) ;
  
          t1.start();
          t2.start();
      }
  }
  </code></pre>