title: Stopping and resuming infinite loop on key input
body: <p>Let's say we have an infinite loop, and we want to put it to sleep for a while, and then resume it. Instead of having a set time, we resume it when we press a key.</p>
  
  <p>For example, in Java we could have:</p>
  
  <pre><code>while(true){
      doSomething();
  }
  </code></pre>
  
  <p>Now, we could make this interruptable in many ways. We want to interrupt it on a key press, so we will have:</p>
  
  <pre><code>boolean running = true;
  ...
  this.addKeyListener(this);
  ...
  @override
  public void keyPressed(KeyEvent e){
      running = false;
  }
  </code></pre>
  
  <p>And then run a method (let's say <code>run</code>), which contains:</p>
  
  <pre><code>while(running){
      doSomething();
  }
  </code></pre>
  
  <p>But then we'd meet one problem: resuming.</p>
  
  <p>So we take the <code>keyPressed</code> method, and change it's body to:</p>
  
  <pre><code>running = !running;
  if(running){
      run();
  }
  </code></pre>
  
  <p>There is just one problem here: the KeyListener won't do anything until the <code>run</code> method is finished. I've tried using threads, where we would have:</p>
  
  <pre><code>private class Runner implements Runnable {
      @Override
      public void run() {
          while (running) {
              doSomething();
          }
      }
  }
  </code></pre>
  
  <p>and in <code>keyPressed</code>:</p>
  
  <pre><code>if(running){
      runner.wait();
  }else{
      runner.notify();
      runner.run();
  }
  running = !running;
  </code></pre>
  
  <p>but in my actual code the <code>doSomething</code> method is code that can't be interrupted (because it handles output to the screen), so <code>thread.wait()</code> can never be called (it will throw exceptions all the time and not actually wait).</p>
  
  <p>So then, to summarize: How does one stop and resume looping something at will using key input in Java?</p>