Do *not* use volatile variables. They are not guaranteed to be atomic.
It's just a compiler hint.

Instead, use synchronized blocks:

class MyThread extends Thread {
  boolean mPaused;
  boolean mStopped;

  public void run() {
    ...
    ...
    mStopped = false;
    mPaused = true or false, depends on your application.
    while (!mStopped) {
      if (waitForResume())
        break;

      // do your thing.
      ...
    }
  }

  public void stopThread() {
    syncrhonized(this) {
      mPaused = false;
      mStopped = true;
      this.notify();
    }
    // optionally, code an extra 'join()' statement if the caller
needs
    // to wait until the thread has completely finished.
  }

  public void pauseThread() {
    syncrhonized(this) {
      mPaused = true;
      this.notify();
    }
  }

  public void resumeThread() {
    syncrhonized(this) {
      mPaused = false;
      this.notify();
    }
  }

  private boolean waitForResume() {
    synchronized(this) {
      if (mStopped)
        return false;

      while (mPaused) {
        this.wait();
      }

      if (mStopped)
        return false;
    }
  }
  ...
  ...
}


Then code that needs to control your thread, just call
myThread.pauseThread() or myThread.resumeThread() and stops the thread
entirely by calling myThread.stopThread();

Note: you could replace 'this' with another object to use for
synchronization.

On Apr 1, 10:06 am, Tom <[email protected]> wrote:
> Try this:
>
> Create a set of volatile variables (toPause, isPaused, toStop,
> isStopped).
>
> Outside the thread, in the methods mentioned previously, set or clear
> the appropriate variables.
> Inside the thread, be checking the appropriate variables to determine
> if the thread needs to be paused or stopped.
>
> Put the use of the variable within synchronized blocks.
> Use wait and notify to avoid busy polling.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to