Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative method to kill thread

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

like image 755
Biscuit128 Avatar asked Nov 04 '22 00:11

Biscuit128


1 Answers

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();
  }
}
like image 101
ddmps Avatar answered Nov 11 '22 08:11

ddmps