title: How To Interrupt/Stop a Working Thread (not current thread) In Java
body: <p><strong>Hello EveryOne</strong></p>
  
  <p>i want to  stop a working thread not current one</p>
  
  <p>i don't want this way </p>
  
  <pre><code>Thread. currentThread().interrupt()
  </code></pre>
  
  <p>because it is only works with current thread in same method block</p>
  
  <p>and i want to block any thread by its name</p>
  
  <blockquote>
    <p>note:</p>
  </blockquote>
  
  <p>this way will not work because my thread is not a current thread and <code>interrupt()</code> method only works for current as i mentioned</p>
  
  <pre><code>Set&lt;Thread&gt; setOfThread = Thread.getAllStackTraces().keySet();
  
  //Iterate over set to find yours
  for(Thread thread : setOfThread){
      if(thread.getId()==yourThread.getId()){
          thread.interrupt();
      }
  }
  </code></pre>
  
  <blockquote>
    <p>the following is my code</p>
  </blockquote>
  
  <pre><code>@Bean(name = "threadPoolExecutor")
  public Executor getAsyncExecutor() {
      ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
      executor.setCorePoolSize(7);
      executor.setMaxPoolSize(42);
      executor.setQueueCapacity(11);
      executor.setThreadNamePrefix("threadPoolExecutor-");
      executor.initialize();
      return executor;
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>@Async("threadPoolExecutor")
  public void MyTask(){
      System.out.println("Currently Executing thread name - " + 
      Thread.currentThread().getName());
      System.out.println("User created with thread pool executor");
  }
  </code></pre>
  
  <p>so when i execute MyTask() it takes a name</p>
  
  <p><strong>My Question</strong> is that i want to stop this process by its name after x of time and only when i request the stop() method as long as the thread still working </p>
  
  <blockquote>
    <p>e.g.</p>
  </blockquote>
  
  <pre><code>@GetMapping(value="/stopThreadByName/{threadname}")
  public String stop(@PathVariable("threadname") String name) {
      //some code to stop the thread by its name
  }
  </code></pre>