title: How to stop threads in Java?
body: <p>I have made a java program with GUI and I want a stop button functionality in which when a user clicks on the stop button, the program must be stopped.</p>
  
  <ol>
  <li><p>In my program, the main thread starts other 10 threads and I want that whenever the stop button has been clicked all the 10 threads must be stopped before the main thread.</p></li>
  <li><p>Second, I also want that whenever any thread of those 10 threads is stopped, it must first close all the resources it had opened before like connection to a database etc.</p></li>
  </ol>
  
  <p>I have implemented the code as answered by ........</p>
  
  <p>Now there is one problem.</p>
  
  <p>My thread class is like this:</p>
  
  <pre><code>public class ParserThread implements Runnable {
      private volatile boolean stopped = false;
  
      public void stopTheThread() {
          stopped = true;
      }
      :
      :
  }
  </code></pre>
  
  <p>And below is the main thread that starts 10 threads from the function start()</p>
  
  <pre><code>public class Main() {
      Thread [] threads;
  
      public void start() {
          for(int i = 0; i &lt; 10; i++) {
              threads[i] = new Thread(new ParserThread());
          }       
      }
  
      public void stop() {
          // code to stop all the threads
      }
  }
  </code></pre>
  
  <p>Now I want to call the stop method of the ParserThread to set "stopped = true" to stop the thread. I want this thing to be done for all the 10 threads.</p>
  
  <p>How can I call that stop method. I want it to be done in the stopAllThreads() method of the Main class.</p>