java – TimerTask替代方案
发布时间:2020-12-15 05:10:50 所属栏目:Java 来源:网络整理
导读:基本上我有2个班级:主要和人口.我想要做的是每秒使用Population.grow()将Population.total增加100.人口已经扩展了另一个类,所以我无法扩展TimerTask. 这是人口的代码: public class Population extends AnotherClass{private int total = 0; void grow(){
|
基本上我有2个班级:主要和人口.我想要做的是每秒使用Population.grow()将Population.total增加100.人口已经扩展了另一个类,所以我无法扩展TimerTask.
这是人口的代码: public class Population extends AnotherClass{
private int total = 0;
void grow(){
this.population = this.population + 100;
}
}
和主类: public class Main{
public static void main(String [] args){
Population population = new Population();
}
}
通常我要做的就是使Population扩展 Timer timer = new Timer(); timer.schedule(grow(),1000); 问题既不是Main也不是Population可以扩展Timer或任何其他类,因为我需要在Main类中声明人口.那我怎么能这样做呢? 解决方法
你可以让它实现Runnable并使用
ScheduledExecutorService.
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(yourRunnable,1,TimeUnit.SECONDS); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
