Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set a infinite loop and break it. (Java threads)

i have set a thread and i want to run it using a loop. so this thread should run in the loop and break in a certain time and again run the loop.

please i have no clue how to do this. can someone guide me.

like image 824
Nubkadiya Avatar asked May 18 '10 05:05

Nubkadiya


1 Answers

Java has a built in mechanism for having a thread do something and then wait for a while to do it again, called Timer. You can put what would be inside your loop inside the Run() method of a TimerTask, and then tell the timer how often you want it done.

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

It is of course your job to shut it down when the program is done.

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

like image 106
Affe Avatar answered Oct 03 '22 21:10

Affe