java - TimerTask 替代方案

标签 java oop

基本上我有 2 个类:MainPopulation。我想要做的是每秒使用 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);

问题是 MainPopulation 都不能扩展 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/

相关文章:

php - 为什么要在 PHP 中使用静态调用?

java - 如何按实例计算方法调用

java - 使用 Selenium 上传文件

java - 我应该如何在一个文件中构建多个类和方法的结构?

java - 无法在 selenium 代码中使用 poi 在 excel 文件中写入输出

java - 从输入流java读取html

Java "Zero-Argument"错误

php - 将对象转换为数组 PHP - 仅公共(public)字段

Java/Python : Integration, 循环更新文本的问题

c++ - 比较没有 RTTI 的抽象类?