3

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?

4

2 回答 2

10

You could make it implement Runnable and use a ScheduledExecutorService.

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 0, 1, TimeUnit.SECONDS);
于 2013-05-21T20:52:10.797 回答
4

try like this

    final Population population = new Population();
    new Timer().schedule(new TimerTask() {
        public void run() {
            population.grow();
        }
    }, 1000);
于 2013-05-21T21:30:39.357 回答