Let's say I have a simple code which increments variable "counter" by 1, every 5 seconds. I would like to stop timer, when "counter" reaches 5. I would like to use object listener for this (listens to certain events). Is this possible?
public class CallMe{
static int counter = 0;
public static void main(String[] args) {
// This code increments counter variable by 1, every 5 seconds.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
counter++;
System.out.println(counter);
}
}, 1000, 5000);
}
}