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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With