title: Java: Producer/Consumer using BlockingQueue: having the consumer thread wait() until another object is queued
body: <p>I've been having some thread related problems recently with a consumer that takes points. Here is the original, which works fine except for taking up a lot of cpu constantly checking the queue. The idea is that cuePoint can be called casually and the main thread keeps going.</p>
  
  <pre><code>import java.util.List;
  import java.util.ArrayList;
  import java.util.concurrent.ArrayBlockingQueue;
  import java.util.concurrent.BlockingQueue;
  
  
  public class PointConsumer implements Runnable {
      public static final int MAX_QUEUE_SIZE=500;
  
      BlockingQueue&lt;Point&gt; queue;
  
      public PointConsumer (){
          this.queue=new ArrayBlockingQueue&lt;Point&gt;(MAX_QUEUE_SIZE);
      }
  
       public void cuePoint(Point p){
          try{
              this.queue.add(p);
          }
          catch(java.lang.IllegalStateException i){}
      }
       public void doFirstPoint(){
          if(queue.size()!=0){
              Point p=queue.poll();
              //operation with p that will take a while
          }
      }
  
      public void run() {
          while(true){
                    doFirstPoint();
          }
      }
  
  }
  </code></pre>
  
  <p>I tried to fix the cpu issue by adding notify() every time the cue function is called, and re-working doFirstPoint() to something like this:</p>
  
  <pre><code>public void doFirstPoint(){
  
      if(queue.size()!=0){
              //operation with p that will take a while
      }
      else{
          try{
              wait();
          }
          catch(InterruptedException ie){}
      }
  }
  </code></pre>
  
  <p>However, I found out that notify() and wait() only work in synchronized functions. When I make doFirstPoint and cuePoint synchronized, the main thread which has called cuePoint will be kept waiting.</p>
  
  <p>I had a few ideas to get around this, including making the thread an object and having it be directly notified, but I wasn't sure if that would cause more problems than it would fix, be very bad form, or simply not work. Is there a simple solution to this problem that I'm missing?</p>