title: While loop with flag
body: <pre><code>public class Simulation extends Thread {
      private volatile boolean loopState = true;
  
      public void stopLoop() {
          loopState = false;
      }
  
      public void run() {     
          try {
              Robot r = new Robot();
  
              while (loopState) {
                  r.keyPress(KeyEvent.VK_LEFT);
                  r.keyRelease(KeyEvent.VK_LEFT);
                  sleep(50);
              }
          } catch (AWTException | InterruptedException e) {}
      }
  }
  </code></pre>
  
  <p>When I launch <code>stopLoop()</code> the <code>while</code> loop below doesn't stop. If I print the value of <code>loopState</code> at the end of the <code>stopLoop()</code> call it returns <code>false</code> but the loop is still executing.</p>
  
  <p>I use this code to call the methods.</p>
  
  <pre><code>Simulation simulation = new Simulation();
      switch (PressedButtonID) {
          case 14:
              simulation.start();
              break;
          case 15:
              simulation.stopLoop();
              break;
  }
  </code></pre>