3

基本的に、 MainPopulationの2 つのクラスがあります。私がやろうとしているのは、毎秒Population.total使用して 100ずつ増やすことです。すでに別のクラスを拡張しているため、拡張できません。Population.grow()PopulationTimerTask

これはのコードですPopulation

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

そしてMainクラス:

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

通常、私が行うことは、次のような更新を実行するためにPopulation拡張することです。Timer

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

クラス内で宣言する必要があるため、問題は拡張も拡張MainPopulationできません。では、どうすればこれを行うことができますか?TimerpopulationMain

4

2 に答える 2

10

Runnableを実装して使用することができますScheduledExecutorService

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

このようにしてみてください

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