0x6C38
0x6C38

Reputation: 7076

TimerTask alternative

Basically I have 2 classes: Main and Population. What I'm trying to do is to increase Population.total by 100 using Population.grow() every second. Population already extends another class so I can't have it extend TimerTask.

This is the code for Population:

public class Population extends AnotherClass{
private int total = 0;
 void grow(){
 this.population = this.population + 100;
 }
}

And the Main class:

public class Main{
 public static void main(String [] args){
 Population population = new Population();
 }
}

Normally what I'd do is just make Population extend Timer to perform updates like this:

 Timer timer = new Timer();
 timer.schedule(grow(), 1000);

The problem is neither Main nor Population can extend Timer or any other class as I need population to be declared inside the Main class. So how can I go about doing this?

Upvotes: 4

Views: 6254

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136122

try like this

    final Population population = new Population();
    new Timer().schedule(new TimerTask() {
        public void run() {
            population.grow();
        }
    }, 1000);

Upvotes: 4

Duncan Jones
Duncan Jones

Reputation: 69399

You could make it implement Runnable and use a ScheduledExecutorService.

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 0, 1, TimeUnit.SECONDS);

Upvotes: 11

Related Questions