title: Can't exit out of a while loop when using threads
body: <p>I know it is not good practice to set a while loop that keeps running until a thread stops running, but I have run out of other ideas. However, even when I resort to this (or something similar to this), I still can't get my program to run properly.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>public void phase1() {
      phase1CompoundLabels = new JLabel[numberOfElements];
      okToShowAlternatives = false;
  
      remove(btnNewButton);
      revalidate();
      repaint();
  
      while (totalNoOfPhase1Trials &gt; 399) {
          Phase1Trial phase1Trial = new Phase1Trial(numberOfElements, elementColors);
  
          // this displays a set of images
          displayComplexStimulus(phase1Trial.getComplexStimulus());
  
          validate();
  
          // after calling this method the images get removed after two
          // seconds and the okToShowAlternatives variable gets its value
          // changed to true
          removeElementsAfterInterval(2000, phase1CompoundLabels);
  
          // while(okToShowAlternatives == false){
          // }
  
          // calling this method displays two images
          // displayAlternatives(phase1Trial.getcorrectImage(),
          // phase1Trial.getincorrectImage(),
          // phase1Trial.getcorrectElementIsOnLeft());
  
  
  private void removeElementsAfterInterval(int milliseconds, JLabel[] labels) {
      Thread compoundThread = new Thread(new Runnable() {
  
          public void run() {
              try {
                  Thread.currentThread().sleep(milliseconds);
                  for (int i = 0; i &lt; labels.length; i++) {
                      remove(labels[i]);
                      revalidate();
                      repaint();
  
                  }
                  okToShowAlternatives = true;
                  System.out.println("OkToShowAlternatives: " + okToShowAlternatives);
  
              } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  Thread.currentThread().interrupt();
              }
  
          }
  
      });
      compoundThread.start();
  }
  </code></pre>
  
  <p>With the while loop (the one with the OkToShowAlternatives in the condition) and the displayAlternatives() method call commented out, as shown, the program up to that point works fine, as the set of images display for two seconds and then get removed from the jpanel. However, when I include the while loop, the program stops displaying the set of images, and I can't even close the jframe. It is completely unresponsive. </p>
  
  <p>However when I included a print statement to see if the value of OkToShowElements variable changes to true, it does. So, shouldn't the condition of the while loop no longer be satisfied and therefore exit out of the while loop and continue onto the next part of the code?</p>