title: How to stop a running Thread in Java
body: <p>I am using a Java based file conversion tool which converts PDF to DOCX, but sometimes while conversion it stuck, if input file size is more then 1 MB and start utilizing 100% CPU and more memory and keep running. I want to stop this continuous thread.</p>
  
  <ol>
  <li>I know <code>stop()</code> function is deprecated. </li>
  <li>Calling  <code>thread.interrupt();</code> is not helping, since thread is keep running.</li>
  <li>There is no loop in the code ...so cannot check for interrupted flag in loop</li>
  </ol>
  
  <p>How to Stop a running Thread t.</p>
  
  <pre><code>public class ThreadDemo implements Runnable {
  
      Thread t;
  
      PdfToDocConversion objPdfToDocConversion;
  
      ThreadDemo() throws InterruptedException {
  
          t = new Thread(this);
          System.out.println("Executing " + t.getName());
          // this will call run() fucntion
          t.start();
  
          Thread.sleep(2000);
  
          // interrupt the threads
          if (!t.interrupted()) {
              System.out.println("Interrupted");
  
              t.interrupt();
  
          }
  
          System.out.println(t.isInterrupted()); // true 
  
          System.out.println(t.getName());
  
          System.out.println(t.isAlive());   /// still true 
  
          // block until other threads finish
          try {
              t.join();
          } catch (InterruptedException e) {
          }
      }
  
      public void run() {
  
          objPdfToDocConversion = new PdfToDocConversion();
          try {
  
  
      objPdfToDocConversion.convertDocToPdf();//inside this function thread got stuck
  
          } catch (InterruptedException e) {
  
              Thread.currentThread().interrupt(); 
              System.out.print(t.getName() + " interrupted:");
              e.printStackTrace();
          } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
  
      public static void main(String args[]) {
          try {
              new ThreadDemo();
          } catch (InterruptedException e) {
                  e.printStackTrace();
          }
      }
  }
  </code></pre>