In that case, use "Timer and TimerTask Classes"
import java.util.Timer;
import java.util.TimerTask;
/**
* Simple demo that uses java.util.Timer to schedule a task
* to execute once 5 seconds have passed.
*/
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
timer.cancel(); //Terminate the timer thread
}
}
public static void main(String args[]) {
new Reminder(5);
System.out.println("Task scheduled.");
}
}
........ The below answer was for the same question which was edited later on ........
In Java 8, You can do this to call a method n times:
But if you put it into a little helper function that takes a couple of parameters
IntStream.range(0, n).forEach(i -> doSomething());
void repeat(int count, Runnable action) {
IntStream.range(0, count).forEach(i -> action.run());
}
This will enable you to do things like this:
repeat(3, () -> System.out.println("Hello!"));
and also this:
repeat(4, this::doSomething);