在Java中,如何在可变的持续时间内逐渐递减到零

  • 本文关键字:持续时间 Java java math timer
  • 更新时间 :
  • 英文 :


我有一个X秒的计时器,我希望Y在偶数的时间内倒数到零,在计时器结束的同时达到0。

例如,如果我的计时器为10秒,值为20,我希望该值每秒下降2。

计时器最好能快速更新,因为它将显示为条形。

谢谢你的帮助!

就上下文而言,这是我正在使用的计时器:

public EventTimer(int seconds) {
// Start timer
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
cooledDown = false;
}
class RemindTask extends TimerTask {
public void run() {
// Ends timer
timer.cancel(); //Terminate the timer thread
cooledDown = true;
}
  • 罗马

编辑:我知道我可以再设置一个计时器,但我的主要目标是逐渐减少

我想到了这个。

public class Counter {
public static void main(String[] args) throws InterruptedException {
int inSeconds = 5;
int countTo = 10;
countToInSeconds(inSeconds, countTo);
}
public static void countToInSeconds(double inSeconds, double countTo) throws InterruptedException {
// Throw Exception if invalid args
if (countTo < 0 || inSeconds < 0){
throw new IllegalArgumentException("CountTo and inSeconds must be positive");
}
// Calculated lerp time
long lerpTime = (long) (1000 / (countTo / inSeconds));
// Count to countTo in inSeconds
for (int i = 1; i <= countTo; i++) {
System.out.println(i);
Thread.sleep(lerpTime);
}
System.out.println("Done! Counted to " + countTo + " in " + inSeconds + " seconds :D");
}
}

它只是一个使用Thread.sleep的常规计时器,但有一个计算的lerp时间。

// This code calculates the wait Time between the sysout statement
long lerpTime = (long) (1000 / (countTo / inSeconds));

因此,通常我们会在每次迭代中等待1000ms(1秒(。但通过将countTo除以inSeconds,我们得到了在下一个sysout调用之前等待的实际时间,即0.5秒。现在我们只需要1000毫秒(1秒(,除以0.5,就可以得到实际的等待时间,以毫秒为单位,即500。

剩余T时间时Y的分数为Y*T/X。这里有一个简单的TimerTask,它勾选X次,从Y(不包括(一直到0.0(包括(。

如果你想在GUI中显示这一点,你必须弄清楚如何将当前值发布到你的UI框架中。请记住,run()运行在定时器线程中,而不是GUI框架线程中,因此您不能直接从TimerTask修改UI。

class RemindTask extends TimerTask {
private int y;
private int x;
private int ticksLeft;
public RemindTask(int Y, int X) {
y = Y;
x = X;
ticksLeft = X;
}
public void run() {
ticksLeft = ticksLeft - 1;
double currentValue = (double) y*ticksLeft/x;
System.out.println(currentValue);
if (ticksLeft == 0) {
cancel();
}
}
}

最新更新