Another way to suspend and resume : Thread Status « Threads « Java






Another way to suspend and resume

Another way to suspend and resume
 
public class AlternateSuspendResume extends Object implements Runnable {

  private volatile int firstVal;

  private volatile int secondVal;

  private volatile boolean suspended;

  public boolean areValuesEqual() {
    return (firstVal == secondVal);
  }

  public void run() {
    try {
      suspended = false;
      firstVal = 0;
      secondVal = 0;
      workMethod();
    } catch (InterruptedException x) {
      System.out.println("interrupted in workMethod()");
    }
  }

  private void workMethod() throws InterruptedException {
    int val = 1;

    while (true) {
      // blocks if suspended is true
      waitWhileSuspended();

      stepOne(val);
      stepTwo(val);
      val++;

      // blocks if suspended is true
      waitWhileSuspended();

      Thread.sleep(200); // pause before looping again
    }
  }

  private void stepOne(int newVal) throws InterruptedException {

    firstVal = newVal;
    // simulate some other lengthy process
    Thread.sleep(300);
  }

  private void stepTwo(int newVal) {
    secondVal = newVal;
  }

  public void suspendRequest() {
    suspended = true;
  }

  public void resumeRequest() {
    suspended = false;
  }

  private void waitWhileSuspended() throws InterruptedException {
    while (suspended) {
      Thread.sleep(200);
    }
  }

  public static void main(String[] args) {
    AlternateSuspendResume asr = new AlternateSuspendResume();

    Thread t = new Thread(asr);
    t.start();

    try {
      Thread.sleep(1000);
    } catch (InterruptedException x) {
    }

    for (int i = 0; i < 10; i++) {
      asr.suspendRequest();

      try {
        Thread.sleep(350);
      } catch (InterruptedException x) {
      }

      System.out.println("dsr.areValuesEqual()=" + asr.areValuesEqual());

      asr.resumeRequest();

      try {
        Thread.sleep((long) (Math.random() * 2000.0));
      } catch (InterruptedException x) {
      }
    }
    System.exit(0);
  }
}

           
         
  








Related examples in the same category

1.Is thread aliveIs thread alive
2.Thread sleepThread sleep
3.Another way to stop a threadAnother way to stop a thread
4.Visual suspend and resumeVisual suspend and resume
5.Thread sleep and interruptThread sleep and interrupt
6.Daemon ThreadDaemon Thread
7.Pausing the Current Thread: a thread can temporarily stop execution.
8.Pausing a Thread: set a variable that the thread checks occasionally, call Object.wait()
9.set Uncaught Exception Handler
10.Monitor a thread's status.
11.Pause the execution
12.Interrupt a thread.
13.Stopping a Thread: set a variable that the thread checks occasionally
14.Determining When a Thread Has Finished
15.Add a delay
16.Pause the execution of a thread using sleep()