Pausing a Thread: set boolean a variable that the thread checks occasionally : Wait Notify « Thread « Java Tutorial






public class Main {
  public static void main(String[] argv) throws Exception {
    MyThread thread = new MyThread();
    thread.start();

    while (true) {
      synchronized (thread) {
        thread.pause = true;
      }
      synchronized (thread) {
        thread.pause = false;
        thread.notify();
      }
    }
  }
}

class MyThread extends Thread {
  boolean pause = false;

  public void run() {
    while (true) {
      synchronized (this) {
        while (pause) {
          try {
            wait();
          } catch (Exception e) {
          }
        }
      }
    }
  }
}








10.21.Wait Notify
10.21.1.Use wait() and notify() from Object class
10.21.2.Monitor a thread's status.
10.21.3.Stopping a Thread: set a boolean variable that the thread checks occasionally
10.21.4.Pausing a Thread: set boolean a variable that the thread checks occasionally