title: What Is The Correct Way To Continuously Loop An Application
body: <p>My question isn't specific to Java but that is the language I'm using to achieve what I want.</p>
  
  <p>I'm experimenting with Bluetooth in Java and have written a simple terminal program i.e. no GUI interface that searches for nearby Bluetooth devices and lists them. My code is as follows:</p>
  
  <pre><code>import javax.bluetooth.*;
  
  public class BluetoothTest implements DiscoveryListener{
  
      private static boolean isAlive = true;
  
      public static void main(String[] args) {
          try {
              LocalDevice ld = LocalDevice.getLocalDevice();
              if (LocalDevice.isPowerOn()){
                  System.out.println("Power On.");
                  System.out.println("Friendly Name: " + ld.getFriendlyName());
                  System.out.println("Address: " + ld.getBluetoothAddress());
                  DiscoveryAgent da = ld.getDiscoveryAgent();
                  da.startInquiry(DiscoveryAgent.GIAC,new BluetoothTest());
                  while (isAlive){
                      /* Sleep */
                      try {
                          Thread.sleep(200);
                      } catch (InterruptedException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }
                  }
              } else {
                  System.out.println("Power Off.");
              }
          } catch (BluetoothStateException e) {
              System.out.println(e.toString());
          }
      }
  
      public void setAlive(boolean status){
          isAlive = status;
      }
  
      public void deviceDiscovered(RemoteDevice rd, DeviceClass dc){
          try{
              System.out.println(rd.getFriendlyName(true));
          } catch (java.io.IOException e){
              System.out.println(e.toString());
          }
      }
  
      public void inquiryCompleted(int discType){
          isAlive = false;
      }
  
      public void servicesDiscovered(int transID, ServiceRecord[] sr){
      }
  
      public void serviceSearchCompleted(int transID, int respCode){
      }
  }
  </code></pre>
  
  <p>The startInquiry() of DiscoveryAgent object returns immediately and any devices that are discovered are returned to the DiscoveryListener interface which I have implemented. The problem is unless I include the while() loop the program will terminate before any devices are discovered.</p>
  
  <p>Just how do applications efficiently stay resident? Is it achieved by having a separate 'working' thread and a main thread which spawns the working thread but itself sleeps until the worker had finished?</p>