I need this for an infinite loop if the user has not canceled it.
Obviously, you can easily add a loop inside your run() method:
new Thread(new Runnable() { public void run() { while (true) {
It is always recommended 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 ask how you can cancel a thread operation from another thread (for example, a UI thread), you can do something like this:
private final volatile running = true; ... new Thread(new Runnable() { public void run() { while (running) {
We need to use volatile boolean so that changes to the field in one thread are visible in another thread.
source share