Suspend.java


// Suspending, resuming, and stopping a thread.

class MyThread implements Runnable {
  Thread thrd;

  boolean suspended;
  boolean stopped;

  MyThread(String name) {
    thrd = new Thread(this, name);
    suspended = false;
    stopped = false;
    thrd.start();
  }

  // This is the entry point for thread.
  public void run() {
    System.out.println(thrd.getName() + " starting.");
    try {
      for(int i = 1; i < 1000; i++) {
        System.out.print(i + " ");
        if((i%10)==0) {
          System.out.println();
          Thread.sleep(250);
        }

        // Use synchronized block to check suspended and stopped.
        synchronized(this) {
          while(suspended) {
            wait();
          }
          if(stopped) break;
        }
      }
    } catch (InterruptedException exc) {
      System.out.println(thrd.getName() + " interrupted.");
    }
    System.out.println(thrd.getName() + " exiting.");
  }

  // Stop the thread.
  synchronized void myStop() {
    stopped = true;

    // The following ensures that a suspended thread can be stopped.
    suspended = false;
    notify();
  }

  // Suspend the thread.
  synchronized void mySuspend() {
    suspended = true;
  }

  // Resume the thread.
  synchronized void myResume() {
    suspended = false;
    notify();
  }
}

class Suspend {
  public static void main(String[] args) {
    MyThread ob1 = new MyThread("My Thread");

    try {
      Thread.sleep(1000); // let ob1 thread start executing

      ob1.mySuspend();
      System.out.println("Suspending thread.");
      Thread.sleep(1000);

      ob1.myResume();
      System.out.println("Resuming thread.");
      Thread.sleep(1000);

      ob1.mySuspend();
      System.out.println("Suspending thread.");
      Thread.sleep(1000);

      ob1.myResume();
      System.out.println("Resuming thread.");
      Thread.sleep(1000);

      ob1.mySuspend();
      System.out.println("Stopping thread.");
      ob1.myStop();
    } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
    }

    // wait for thread to finish
    try {
      ob1.thrd.join();
    } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
    }

    System.out.println("Main thread exiting.");
  }
}


Results

C:\ece538\java_thread>java Suspend
My Thread starting.
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
Suspending thread.
Resuming thread.
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
Suspending thread.
Resuming thread.
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
101 102 103 104 105 106 107 108 109 110
111 112 113 114 115 116 117 118 119 120
Stopping thread.
121 My Thread exiting.
Main thread exiting.


Maintained by John Loomis, updated Mon Nov 19 21:28:53 2012