Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 1000
Alex Haycock Avatar asked Mar 21 '12 20:03

Alex Haycock


1 Answers

I need this to loop infinitely unless cancelled by the user.

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 volatile running = true;
...
new Thread(new Runnable() {
    public void run() {
        while (running) {
           // do something in the loop
        }
    }
}).start();
...

// later, in another thread, you can shut it down by setting running to false
running = false;

We need to use a volatile boolean so that changes to the field in one thread are seen in the other thread.

like image 193
Gray Avatar answered Oct 15 '22 10:10

Gray