2013-05-21 39 views
3

基本上我有2類:人口。我想要做的是每秒鐘使用Population.grow()Population.total增加100。 Population已經擴展了另一個班級,所以我不能延長TimerTaskTimerTask替代

這是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); 

問題是既不Main也不Population可以延伸Timer或任何其他類如我需要​​到Main類中被聲明。那麼我該怎麼做呢?

+3

創建擴展的定時器將InnerClass。當它觸發時,你可以調用OuterClass。您也可以查看Observer設計模式。 – Spidy

+1

@Spidy你爲什麼不做出答案? –

+0

沒有時間獲得高質量的響應。 Evgeniy的回答就是我所說的(除非增長是私密的,否則你需要在課堂中使用計時器代碼) – Spidy

回答

9

您可以使其執行Runnable並使用ScheduledExecutorService

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

嘗試這樣

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