Alex Haycock Alex Haycock - 1 month ago 6
Android Question

How do you loop a thread?

I have a thread containing a runnable.
I need this to loop infinitely unless cancelled by the user.
I have no idea how to go about this. All help is greatly appreciated.
Cheers.

Answer

Obviously you can easily add a loop inside of your run() method:

  new Thread(new Runnable() {
      public void run() {
          while (true) {
             // do something in the loop
          }
      }
  }).start();

It's always a good idea to check for thread interruption:

  new Thread(new Runnable() {
      public void run() {
          // loop until the thread is interrupted
          while (!Thread.currentThread().isInterrupted()) {
             // do something in the loop
          }
      }
  }).start();

If you are asking about how you can cancel a thread operation from another thread (such as a UI thread) then you can do something like this:

  private final AtomicBoolean running = new AtomicBoolean(true);
  ...
  new Thread(new Runnable() {
      public void run() {
          while (running.get()) {
             // do something in the loop
          }
      }
  }).start();
  ...

  // later, in another thread, you can shut it down by setting running to false
  running.set(false);

We need to use an AtomicBoolean (or a volatile boolean) so that changes to the field in one thread are seen in the other thread.

If you add more details to your question on what you are actually trying to accomplish, I can provide a better answer.