基本上,我有两个类:、Main和Population。我想做的是每秒钟使用Population.grow()将Population.grow()增加100。Population已经扩展了另一个类,所以我不能让它扩展TimerTask。
这是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类中声明population。那我该怎么做呢?
发布于 2013-05-21 20:52:10
您可以让它实现Runnable并使用ScheduledExecutorService。
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 0, 1, TimeUnit.SECONDS);发布于 2013-05-21 21:30:39
试着像这样
final Population population = new Population();
new Timer().schedule(new TimerTask() {
public void run() {
population.grow();
}
}, 1000);https://stackoverflow.com/questions/16679233
复制相似问题