Java 每X秒运行一个方法
我正在用Java创建一个基于文本的游戏,作为我自己的第一个官方程序。 这是一个包含饥饿、口渴和体温变量的生存游戏 比方说,我希望饥饿和口渴每5秒左右减少一次。 目前我唯一能去上班的就是这个。 这无疑会减少数字,但它会在2秒内从100变为0Java 每X秒运行一个方法,java,timer,Java,Timer,我正在用Java创建一个基于文本的游戏,作为我自己的第一个官方程序。 这是一个包含饥饿、口渴和体温变量的生存游戏 比方说,我希望饥饿和口渴每5秒左右减少一次。 目前我唯一能去上班的就是这个。 这无疑会减少数字,但它会在2秒内从100变为0 public void run(){ while(running){ long now = System.nanoTime(); delta += (now - lastTime) / ns; lastTim
public void run(){
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
tick();
delta--;
}
}
private void tick(){
Health.playerHealth.tick();
}
///////////////////////////////////////////////
public static Health playerHealth = new Health();
private static int hunger = 100;
private static int thirst = 100;
private static double bodyTemperature = 98.6;
public void tick(){
depleteHunger();
depleteThirst();
depleteBodyTemperature();
}
public void depleteHunger(){
hunger--;
}
public void depleteThirst(){
thirst--;
}
我也试过这个计时器,但它只等我输入的5秒,然后立即从100减少到0
private void tick(){
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
depleteHunger();
depleteThirst();
depleteBodyTemperature();
}
}, 0, 5000);
}
可能您可以查看计时器的
时间表固定日期:
示例:
Timer timerObj = new Timer(true);
timerObj.scheduleAtFixedRate(timerTask, 0, interval));
这种方法基本上实现了您希望实现的目标:以特定的时间间隔执行任务。
您需要通过重写run()
方法初始化TimerTask
对象,并将您的逻辑放入其中(正如您在代码中提到的那样)。final int TICKS\u PER\u SECOND=20;
最终整数滴答时间=1000/滴答每秒;
(跑步时){
最终长启动时间=System.currentTimeMillis();
//一些行动
最终长结束时间=System.currentTimeMillis();
最终长差=结束时间-开始时间;
如果(差异<勾选时间){
试一试{
睡眠(滴答时间-差异);
}捕获(例外e){
e、 printStackTrace();
}
}
}
找到了解决方案
public class HealthStatsTimer extends TimerTask {
public void run() {
Health.playerHealth.depleteHunger();
Health.playerHealth.depleteThirst();
Health.playerHealth.depleteBodyTemperature();
}
}
//////////////////////
public static void main(String[] args){
new Stranded();
Timer timer = new Timer();
timer.schedule(new HealthStatsTimer(), 5000, 5000);
}
public class HealthStatsTimer extends TimerTask {
public void run() {
Health.playerHealth.depleteHunger();
Health.playerHealth.depleteThirst();
Health.playerHealth.depleteBodyTemperature();
}
}
//////////////////////
public static void main(String[] args){
new Stranded();
Timer timer = new Timer();
timer.schedule(new HealthStatsTimer(), 5000, 5000);
}