5

I have been looking for ways to kill a thread and it appears this is the most popular approach

public class UsingFlagToShutdownThread extends Thread {
  private boolean running = true;
  public void run() {
    while (running) {
      System.out.print(".");
      System.out.flush();
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ex) {}
    }
    System.out.println("Shutting down thread");
  }
  public void shutdown() {
    running = false;
  }
  public static void main(String[] args)
      throws InterruptedException {
    UsingFlagToShutdownThread t = new UsingFlagToShutdownThread();
    t.start();
    Thread.sleep(5000);
    t.shutdown();
  }
}

However, if in the while loop we spawn another another object which gets populated with data (say a gui that is running and updating) then how do we call back - especially considering this method might have been called several times so we have many threads with while (running) then changing the flag for one would change it for everyone?

thanks

Biscuit128
  • 5,218
  • 22
  • 89
  • 149
  • 4
    **No a solution, but a best practice:** Declare your flag `running` as `volatile`. – Eng.Fouad Apr 05 '13 at 14:48
  • The best approach to thread-killing is to not try. If there is any way in which you can design an app so that threads do not need to be killed until the OS kills them at process termination, you should do exactly that. – Martin James Apr 05 '13 at 14:56
  • but if the run method has as infinite loop, even if you close the gui the thread is pumping data in to, it still wont die :( – Biscuit128 Apr 05 '13 at 14:57
  • possible duplicate of [How can I kill a thread? without using stop();](http://stackoverflow.com/questions/5915156/how-can-i-kill-a-thread-without-using-stop) – Nathan Hughes Apr 05 '13 at 15:21
  • Sorry, my close vote may have been wrong, I was distracted by the first part, which shows a common-but-lousy way to stop a thread. But the second part seems very vague and needs a better example. – Nathan Hughes Apr 05 '13 at 15:29
  • @SkyR - it will if it's a daemon. – Martin James Apr 05 '13 at 16:11

2 Answers2

2

One approach with these problems is to have a Monitor class which handles all the threads. It can start all necessary threads (possibly at different times/when necessary) and once you want to shutdown you can call a shutdown method there which interrupt all (or some) of the threads.

Also, actually calling a Threads interrupt() method is generally a nicer approach as then it will get out of blocking actions that throw InterruptedException (wait/sleep for example). Then it will set a flag that is already there in Threads (which can be checked with isInterrupted() or checked and cleared with interrupted(). For example the following code can replace your current code:

public class UsingFlagToShutdownThread extends Thread {
  public void run() {
    while (!isInterrupted()) {
      System.out.print(".");
      System.out.flush();
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ex) { interrupt(); }
    }
    System.out.println("Shutting down thread");
  }
  public static void main(String[] args)
      throws InterruptedException {
    UsingFlagToShutdownThread t = new UsingFlagToShutdownThread();
    t.start();
    Thread.sleep(5000);
    t.interrupt();
  }
}
ddmps
  • 4,350
  • 1
  • 19
  • 34
  • 2
    Do you mean `while (!isInterrupted())` ? – Mark Bolusmjak Apr 05 '13 at 15:11
  • 1
    This is the recommended way in a book named `Java Concurrency in Practice` which is co-authored by JDK concurrent designers (Tim Peierls Joshua Bloch Joseph Bowbeer David Holmes and Doug Lea)。 `Thread.stop` is absolutely deprecated. – Henry Leu Apr 06 '13 at 05:41
0

i added a utlility class which essentially had a static map and methods.

the map was of type Long id, Thread thread. I added two methods one to add to the map and one to stop the thread via the use of interrupt. This method took the id as a parameter.

I also changed my loop logic from while true, too while ! isInterrupted. Is this approach ok or is this bad programming style/convention

thanks

Biscuit128
  • 5,218
  • 22
  • 89
  • 149