Alternative method for killing a thread

I was looking for ways to kill the thread, and it seems like 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 create another object that is populated with data (for example, gui, which works and updates), then how will we call back - especially considering that this method could be called several times, so we have many threads with the show (running), and then changing the flag for one would change it for everyone?

thank

+5
source share
2 answers

, Monitor, . (, / ), , , ( ) .

, Thread interrupt() , , InterruptedException (, wait/sleep). , Threads ( isInterrupted() interrupted()). , :

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();
  }
}
+2

utlility, .

Long id, Thread thread. : , , , . .

, , ! isInterrupted. /

0

All Articles