[英]Java: Speeding up and slowing down time
我试图弄清楚设置任意时间的逻辑,然后让时间以不同的速度“回放”(例如.5x或4x实时)。
这是我到目前为止的逻辑,它将以正常速度回放时间:
import java.util.Calendar;
public class Clock {
long delta;
private float speed = 1f;
public Clock(Calendar startingTime) {
delta = System.currentTimeMillis()-startingTime.getTimeInMillis();
}
private Calendar adjustedTime() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis()-delta);
return cal;
}
public void setPlaybackSpeed(float speed){
this.speed = speed;
}
public static void main(String[] args){
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 4, 4, 4, 4, 4);
Clock clock = new Clock(calendar);
while(true){
System.out.println(clock.adjustedTime().getTime());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
我无法弄清楚逻辑中需要使用“速度”属性的位置。
下面的代码给出了如何设计这样一个时钟的示例,该时钟具有double spped
和long startTime
的内部状态。 它公开了一个发布方法getTime()
,它将返回自1970年1月1日午夜以来以毫秒为单位的调整时间。请注意,调整发生在startTime
。
计算调整时间的公式很简单。 首先通过startTime
减去currentTimeMillis()
获取实时timedelta,然后将此值乘以speed
以获得调整后的timedelta,然后将其添加到startTime
以获得结果。
public class VariableSpeedClock {
private double speed;
private long startTime;
public VariableSpeedClock(double speed) {
this(speed, System.currentTimeMillis());
}
public VariableSpeedClock(double speed, long startTime) {
this.speed = speed;
this.startTime = startTime;
}
public long getTime () {
return (long) ((System.currentTimeMillis() - this.startTime) * this.speed + this.startTime);
}
public static void main(String [] args) throws InterruptedException {
long st = System.currentTimeMillis();
VariableSpeedClock vsc = new VariableSpeedClock(2.3);
Thread.sleep(1000);
System.out.println(vsc.getTime() - st);
System.out.println(System.currentTimeMillis() - st);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.