簡體   English   中英

每X秒運行一次方法

[英]Run a method every X seconds

我正在用Java創建一個基於文本的游戲,這是我自己的第一個官方程序。 它是帶有飢餓,口渴和體溫變量的生存游戲。

可以說,我希望飢餓感和飢餓感每5秒左右減少一次。 目前,我只能上班的是這個。 這肯定會減少數字,但會在2秒內從100變為0。

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秒我把THEN降低從100到0瞬間

private void tick(){

Timer t = new Timer();
  t.schedule(new TimerTask() {
    @Override
    public void run() {
      depleteHunger();
      depleteThirst();
      depleteBodyTemperature();
    }
  }, 0, 5000);
}

可能您可以看看計時器的scheduleAtFixedRate

示例示例:

Timer timerObj = new Timer(true);
timerObj.scheduleAtFixedRate(timerTask, 0, interval));

該方法基本上可以實現您想要實現的目標:以特定的時間間隔執行任務。 您需要通過覆蓋run()方法並將邏輯放入其中來初始化TimerTask對象(正如您在代碼中也提到的那樣)。

final int TICKS_PER_SECOND = 20;
final int TICK_TIME = 1000 / TICKS_PER_SECOND;

while (running) {
    final long startTime = System.currentTimeMillis();
    // some actions
    final long endTime = System.currentTimeMillis();
    final long diff = endTime - startTime;

    if (diff < TICK_TIME) {
        try {
            Thread.sleep(TICK_TIME - diff);
        } catch (Exception 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM