title: How to pause a thread instantly?
body: <p>I have a thread with boolean field "paused" which I use to pause the thread.</p>
  
  <pre><code>public void run() {
      while (running) {
          if (!paused) {
              //HERE I do some operations
          }
      }
  }
  </code></pre>
  
  <p>But this solution give me a problem:</p>
  
  <p>when I press a button that assigns true to the field "paused", the thread before going on pause completes all operations in the if block. </p>
  
  <p>What can I do to pause instantly the thread?</p>
  
  <p>OR</p>
  
  <p>What can I do to force the button callback to be executed at the end of the current iteration?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I solved in this manner:</p>
  
  <pre><code>public void run() {
      while (running) {
          synchronized(paused) {
              if (!paused) {
              //HERE I do some operations
              }
          }
      }
  }
  
  public void disablePause() {
      synchronized(paused) {
          paused = false;
      }
  }
  
  public void pause() {
      synchronized(paused) {
          paused = true;
      }
  }
  </code></pre>
  
  <p>paused now is a Boolean object. The main UI thread that executes the button callback function (that call pause(), do some operations and call disablePause()), waits until paused is released by my custom thread(that is at the end of current iteration of while loop). I have still a doubt:
  is it a good practice?</p>