Suspending, Resuming, and Stopping Threads

The following example illustrates how the wait( ) and notify( ) methods that are inherited from Object can be used to control the execution of a thread.


class NewThread implements Runnable {
  String name; // name of thread
  Thread t;
  boolean suspendFlag = false;

  NewThread(String threadname) {
    name = threadname;
    t = new Thread(this, name);
    t.start(); // Start the thread
  }

  public void run() {
    try {
      for (int i = 5; i > 0; i--) {
        System.out.println(name + ": " + i);
        Thread.sleep(500);
        synchronized (this) {
          while (suspendFlag) {
            wait();
          }
        }
      }
    } catch (InterruptedException e) {
      System.out.println(name + " interrupted.");
    }
    System.out.println(name + " exiting.");
  }

  void suspend() {
    suspendFlag = true;
  }

  synchronized void resume() {
    suspendFlag = false;
    notify();
  }
}

public class Main {
  public static void main(String args[]) throws Exception {
    NewThread ob1 = new NewThread("One");
    NewThread ob2 = new NewThread("Two");
    Thread.sleep(1000);
    ob1.suspend();
    Thread.sleep(2000);
    ob1.resume();
    ob2.suspend();
    Thread.sleep(3000);
    ob2.resume();
  }
}
Home 
  Java Book 
    Thread Conncurrent  

Thread:
  1. Multithreaded Programming
  2. The Main Thread
  3. Thread Name
  4. Thread sleep
  5. Thread Creation
  6. isAlive( ) and join( )
  7. Thread Priorities
  8. Thread Synchronization
  9. Interthread Communication
  10. Suspending, Resuming, and Stopping Threads
  11. Handle Uncaught Exception
  12. ThreadLocal variables