TimerTask替代方案

0x6*_*C38 3 java oop

基本上我有2个班级:主要人口.我要做的是每秒增加Population.total100 Population.grow().Population已经扩展了另一个类,所以我不能扩展它TimerTask.

这是以下代码Population:

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

Main班级:

public class Main{
 public static void main(String [] args){
 Population population = new Population();
 }
}
Run Code Online (Sandbox Code Playgroud)

通常我要做的就是make Populationextend Timer来执行这样的更新:

 Timer timer = new Timer();
 timer.schedule(grow(), 1000);
Run Code Online (Sandbox Code Playgroud)

问题既不是MainPopulation不能扩展Timer或任何其他类,因为我需要populationMain类中声明.那我怎么能这样做呢?

Dun*_*nes 9

你可以让它实现Runnable并使用一个ScheduledExecutorService.

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 0, 1, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)