How do you scroll the thread?

I have a stream containing runnable. I need this for an infinite loop unless the user cancels it. I have no idea how to do this. All help is much appreciated. Greetings.

+4
source share
1 answer

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) { // do something in the loop } } }).start(); 

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) { // 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 volatile boolean so that changes to the field in one thread are visible in another thread.

+9
source

Source: https://habr.com/ru/post/1402749/


All Articles