title: How to use a flag to restart an action in a Thread?
body: <p>I tried using a volatile boolean to act as a flag to stop/start/restart the action in the thread, however it does not work. It just keeps on going forever and never terminates. Any help on how to properly do this or why my code does not work will be greatly appreciated. Thanks in advance.</p>
  
  <pre><code>public class thread {
  
      public static int i = 0;
      private static Thread print = null;
      private static printThread runnable = null;
  
      public static void main(String[] args) {
          runnable = new printThread();
          print = new Thread (runnable);
          print.start();
  
          System.out.println("Starting");
          runnable.begin();
          if(i &gt; 5)
          {
              runnable.terminate();
          }
  
          i = 10;
          runnable.begin();
          if(i &gt; 15)
          {
              runnable.terminate();
          }
      }
  
      public static final void print()
      {
          System.out.println(i);
          i++;
      }
  
      public static final class printThread implements Runnable {
          private volatile boolean running = false;
  
          public void terminate() {
              running = false;
          }
  
          public void begin() {
              running = true;
          }
  
          public boolean isRunning() {
              return running;
          }
  
          public void run() {
              while(true)
              {
                  if(running)
                  {
                      print();
                  }
  
                  else
                  {
  
                  }
              }
          }
      }
  }
  </code></pre>