0

below is a simplified version of the wait-notify scenario I'm trying to implement and I'm really struggling to make it work. I'm completely missing how to invoke notify() on object instance of Class A, and am not sure what to put in the synchronized() parenthesis, and why.

Appreciate any help. Thanks

public class A implements Runnable{

private B b;

@Override
public void run()
{
  b = new B()
  Thread bThread = new Thread(b);
  bThread.start()

  synchronized(this)
  {
    while(something)
   {
     try
     {
       wait();
     }
     catch (Exception e){}
   }
  }
 }
}



public class B implements Runnable{

@Override
public void run()
{
  doSomething();
  synchronized(this)
  {
   try
   {
     notify();
   }
   catch (Exception e){}
  }
 }
}
  • 1
    [Use Google before SO...](http://stackoverflow.com/questions/886722/how-to-use-wait-and-notify-in-java) – bcsb1001 Sep 05 '15 at 15:28
  • 2
    For the wait/notify mechanism to work, two threads have to hold a **reference to the same object**, have a synchronized block on it, and within that block call that instance's `wait()` or `notify()`. A shared object is a must. – RealSkeptic Sep 05 '15 at 15:28
  • Or you can [search this site for similar questions as well](http://stackoverflow.com/search?q=%5Bjava%5D+wait+notify+synchronize). We probably don't need yet another of the same question since high quality answers already exist and are easy to find. – Hovercraft Full Of Eels Sep 05 '15 at 15:31
  • 1
    ... Also for wait/notify to work, you should change state in the notify block which you check in a loop in the wait block. – Peter Lawrey Sep 05 '15 at 15:43
  • As a newbie it'sa little confusing to know which object to invoke wait() notify() on and which to put in the synchronise parenthesis, and why. Turned out for my example I needed to synchronize(bThread) and invoke both wait() and notify() on bThread. Thanks for the links. – Patrick Wallace Sep 06 '15 at 11:12

0 Answers0