0

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);
    }   
}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
rootpanthera
  • 2,731
  • 10
  • 33
  • 65
  • It sure is possible, but you would need to make those events, and you would have to create listeners that would listen to those events – greedybuddha May 15 '13 at 15:42

3 Answers3

1

It is very much possible indeed. There are two interfaces in java.util Observer and Observable. You can use these interfaces to implement the Observer Pattern. Just google with "Observable Examples" and you will find plenty of resources.

All you need to do is implement this class as Observable and create another class as Observer. When your counter reach 5, all you need to do is to call the notifyObservers() method and it will fire an event for all the registered observers.

Raza
  • 856
  • 6
  • 8
  • Note there are serious [problems with Java's Observer interface](https://stackoverflow.com/questions/46380073/observer-is-deprecated-in-java-9-what-should-we-use-instead-of-it). – jaco0646 Feb 28 '19 at 15:59
0

You need to implement an Observer pattern for your variable.

The class containing your counter should maintain a collection of very class that wants to be notified about what counter is. Then when counter reaches 5, you send the notification to all the listeners.

@Override
public void run() {
    counter++;
    System.out.println(counter);
    if(counter == 5) {
        notify();
    }
}

private void notify() {
    for(ChangeListener l : listeners) {
        l.stateChanged(new ChangeEvent(counter));
    }
}

some other class:

class Obs implements ChangeListener {
    @Override
    public void stateChanged(ChangeEvent e) {
        System.out.println(e);
    }
}
Aboutblank
  • 697
  • 3
  • 14
  • 31
-1

You can call the cancel method on your TimerTask :

  @Override
    public void run() {

        counter++;
        if(counter == 5) {
          this.cancel();
        }
        System.out.println(counter);

    }
gma
  • 2,563
  • 15
  • 14
  • I know. But I'm interested in object listeners. Like .. fire certain code when counter reaches 5. Like in Android (DialogInterface.OnClickListener) is interface which provides method and (users )custom code, when Dialog is clicked. – rootpanthera May 15 '13 at 15:44