我有一個課程,可以以不同的速度回放過去的時間。在我下面的示例代碼中,我以60x播放。Java:時間漂移
我注意到時間每隔10秒鐘就會漂移一秒鐘左右,我在想如何處理它。
import java.util.Calendar;
public class Clock {
long delta;
long lastCalledTime;
long startingTime;
private float speed = 1f;
public synchronized long getAdjustedTimeMillis() {
long time = (System.currentTimeMillis() - (delta));
long val = (startingTime + (long) ((time - lastCalledTime) * speed));
return val;
}
public synchronized void setPlaybackSpeedFromTime(float speed, long startingTime) {
this.startingTime = startingTime;
this.delta = System.currentTimeMillis() - startingTime;
this.speed = speed;
this.lastCalledTime = System.currentTimeMillis() - delta;
}
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 4, 4, 4, 4, 4);
Clock clock = new Clock();
clock.setPlaybackSpeedFromTime(60f, calendar.getTimeInMillis());
for (int i = 0; i < 1000; i++) {
calendar.setTimeInMillis(clock.getAdjustedTimeMillis());
System.out.println(calendar.getTime());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
這是我得到的輸出:
Tue May 04 04:04:04 PDT 2010
Tue May 04 04:05:06 PDT 2010
Tue May 04 04:06:06 PDT 2010
Tue May 04 04:07:06 PDT 2010
Tue May 04 04:08:06 PDT 2010
Tue May 04 04:09:06 PDT 2010
Tue May 04 04:10:06 PDT 2010
Tue May 04 04:11:06 PDT 2010
Tue May 04 04:12:06 PDT 2010
Tue May 04 04:13:07 PDT 2010
Tue May 04 04:14:07 PDT 2010
Tue May 04 04:15:07 PDT 2010
Tue May 04 04:16:07 PDT 2010
Tue May 04 04:17:07 PDT 2010
Tue May 04 04:18:07 PDT 2010
Tue May 04 04:19:07 PDT 2010
Tue May 04 04:20:07 PDT 2010
Tue May 04 04:21:07 PDT 2010
Tue May 04 04:22:07 PDT 2010
Tue May 04 04:23:08 PDT 2010
Tue May 04 04:24:08 PDT 2010
正如你可以看到 「秒」 漂移。我想要的是:
Tue May 04 04:04:04 PDT 2010
Tue May 04 04:05:04 PDT 2010
Tue May 04 04:06:04 PDT 2010
Tue May 04 04:07:04 PDT 2010
Tue May 04 04:08:04 PDT 2010
Tue May 04 04:09:04 PDT 2010
Tue May 04 04:10:04 PDT 2010
Tue May 04 04:11:04 PDT 2010
Tue May 04 04:12:04 PDT 2010
Tue May 04 04:13:04 PDT 2010
Tue May 04 04:14:04 PDT 2010
Tue May 04 04:15:04 PDT 2010
Tue May 04 04:16:04 PDT 2010
Tue May 04 04:17:04 PDT 2010
Tue May 04 04:18:04 PDT 2010
Tue May 04 04:19:04 PDT 2010
Tue May 04 04:20:04 PDT 2010
Tue May 04 04:21:04 PDT 2010
Tue May 04 04:22:04 PDT 2010
Tue May 04 04:23:04 PDT 2010
Tue May 04 04:24:04 PDT 2010
嗯,問題很簡單 - Thread.sleep不是一個確切的函數,也沒有考慮處理時間,這會在許多(很多)迭代中累積。不確定如何解決它雖然 – Alex