2013-05-14 113 views
0

我试图弄清楚设置任意时间的逻辑,然后让这个时间以不同的速度(例如.5x或4x实时)“回放”。Java:加快速度并减缓时间

这里是我有迄今为止的逻辑,其将回放时间以正常速度:

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(); 
      } 
     } 

    } 


} 

遇到麻烦搞清楚了“速度”属性需要在逻辑中使用。

+0

实时与您的“定制”时钟之间的关系看起来很简单。也就是说,对于在现实世界中经历的每一秒钟,你的时钟都会以“速度”秒钟来标记。 'T_clock =速度* T_real'。剩下的是你如何定义你的时钟接口。 – 2013-05-14 02:59:18

+1

如果你只需要毫秒的时间,Calender的矫枉过正是非常昂贵的。我会使用'long'和'System.currentTimeMillis()'; – 2013-05-14 04:38:21

回答

2

下面的代码举例说明了如何设计这样一个时钟,该时钟的内部状态为double sppedlong startTime。它公开了发布方法getTime(),它将返回自1970年1月1日午夜以来的调整时间(以毫秒为单位)。请注意,调整发生在startTime之后。

计算调整时间的公式很简单。首先通过减去currentTimeMillis(),startTime,然后乘以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); 

    } 
}