title: How do I avoid busy loop in Java Thread with callback function
body: <p>I am trying to figure out how to eliminate a busy loop in a thread I have in Java.  The thread does nothing but wait for a callback from the Listener class.  The thread class looks something like this:</p>
  
  <pre><code>class MyThread implements Runnable, MessageListener{
    private Listen Listener;
  
    public MyThread(){
      Listener = new Listener(this);
    }
  
    public void run(){
      while(true){}
    }
  
    public void messageReceived(Message m){
      //do stuff
    }
  }
  </code></pre>
  
  <p>I have tried to make this code as simple as possible.  The idea is that Listener is waiting to receive some data from a serial port and when a message is received the thread will do some processing on it. I would prefer to use some synchronized variables such as a BlockingQueue of Message but I can't modify the Listener code.  The issue, of course, is that the run loop eats up processor cycles.  My questions:</p>
  
  <p>If I wait or sleep in the run loop will the function call still work as expected? (I'm not sure how to test that this works 100% of the time).</p>
  
  <p>Is there some better way to avoid this loop altogether?</p>