How to set an infinite loop and break it. (Java Streams)

I have set up a thread and I want to start it with a loop. therefore this thread must run in a loop and interrupt at a specific time and start the loop again.

please i don't know how to do this. can anyone guide me.

+2


a source to share


5 answers


Assuming you are running JDK 1.5 or newer (where the memory model has been refined and improved), you can use

public class MyRunnable extends Runnable
{
   private volatile boolean cancelled;

   public void run() {
      while (!cancelled) { 
         doStuff();
      }
   }

   public void cancel()
   {
      cancelled = true;  
   }

   public boolean isCancelled() {
      return cancelled;
   }
}j

      



Alternatively use java.util.concurrent.Future and FutureTask which supports cancellation out of the box.

+6


a source


Java has a built-in mechanism for a thread to do something and then wait again to do it again is called Timer

. You can put what would be inside a loop inside a method Run()

TimerTask

and then tell the timer how often you want it.

TimerTask task = new TimerTask() {
  @Override
  public void run() {
    //do some processing
  }
};

Timer timer = new Timer();
timer.schedule(task, 0l, 1000l); //call the run() method at 1 second intervals

      



Of course, your job is to close it when the program is done.

http://java.sun.com/javase/6/docs/api/java/util/Timer.html

+12


a source


I feel like we are lacking performers!

There is a ScheduledExecutorService function that you can use to start a task and then run it after a specific time. It's similar to TimerTask, but easier to manage and improve.

private final ScheduledExecutorService scheduler = 
                           Executors.newScheduledThreadPool(1);
 scheduler.scheduleAtFixedRate(new Runnable() {
            public void run() {
                //do work here  
            }
    }, 1, TimeUnit.SECONDS);

      

The runner will check this task every second and can also return a ScheduledFuture that can be used to cancel or get a result (if you are using Callable instead of runnable).

Edit: CPerkins brings up a good point. How do we cancel after a certain time and then launch. It is a little bit, but I believe it is being done.

    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final ExecutorService executor = Executors.newFixedThreadPool(1);

public void execute(){
    executor.submit(scheduleTask());
}
public Runnable scheduleTask(){
    return new Runnable() {
        public void run() {
            final ScheduledFuture cancel = scheduler.scheduleAtFixedRate(new Runnable() {
                public void run() {
                    // do work here
                }
            }, 0, 1, TimeUnit.SECONDS);
            scheduler.schedule(new Runnable() {
                public void run() {
                    cancel.cancel(true);
                    execute();
                }
            }, 1, TimeUnit.MINUTES);
        }
    };
}

      

+5


a source


I can only give you some suggestion. You can set a flag as isThreadRunning and then when this flag is true you start the loop, if it is not you exited the loop. About starting the loop again, I think you can create a new thread for it. Here's a snippet of code:

public class A extends Thread {
  public boolean isThreadRunning = true;
  public void run() {
    while(isThreadRunning) {
    // do task
    }    
  }
}

      

When a certain time occurs, or another thread wants to stop this thread, you can simply call A.isThreadRunning = false;

0


a source


Write your method to start your thread like this

public void run(){
   while (true){
       if (condition){
          // your logic
       }
       java.lang.Thread.sleep(1000L);
   }
}

      

In the above code, the loop is an infinite loop that will execute every second (1000 milliseconds) and your logic will only execute if the condition is met.

If you want to extend the pause time to 2 seconds, change 1000L

to2000L

0


a source







All Articles