基本上我有 2 个类:Main 和 Population。我想要做的是每秒使用 Population.grow()
将 Population.total
增加 100。 Population
已经扩展了另一个类,所以我不能让它扩展 TimerTask
。
这是人口
的代码:
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
或任何其他类,因为我需要 population
来在 Main
类中声明。那么我该怎么做呢?
最佳答案
你可以让它实现 Runnable
并使用 ScheduledExecutorService
.
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 0, 1, TimeUnit.SECONDS);
关于java - TimerTask 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16679233/