Timing is (nearly) everything. (in an animation)

/**
 *
 * @author Chet
 */
public class UtilTimerDemo extends TimerTask {
    
    private static long prevTime = 0;
    private static long startTime = 0;
    private static final long DELAY = 100;
    private static final long DURATION = 5 * DELAY;
    private static final long PROCESSING_TIME = 30;
    private static final long INITIAL_PROCESSING_TIME = 2 * DELAY;
    private static Timer timer = null;
    private boolean firstTime = true;
    private static boolean runningFixedRate = false;
    
    /** 
     * This method will be called during every tick of the Timers.
     * We insert an artificial delay each time, to simulate some processing.
     * The first time through, this delay is greater than the delay between
     * timing events, so that we can see how this hiccup is handled by
     * fixed-rate and fixed-delay timers.
     */
    public void run() {
        long nowTime = System.currentTimeMillis();
        long elapsedTime = nowTime - prevTime;
        long totalTime = nowTime - startTime;
        System.out.println("Elapsed time = " + elapsedTime);
        if (totalTime > DURATION) {
            timer.cancel();
        }
        prevTime = nowTime;
        try {
            if (firstTime) {
                Thread.sleep(INITIAL_PROCESSING_TIME);
                firstTime = false;
            } else {
                Thread.sleep(PROCESSING_TIME);
            }
        } catch (Exception e) {}
    }
    
    public UtilTimerDemo() {
        firstTime = true;
    }
    
    public static void main(String[] args) {
        // Start and run a fixed-delay timer
        timer = new Timer();
        startTime = prevTime = System.currentTimeMillis();
        System.out.println("Fixed Delay Times");
        timer.schedule(new UtilTimerDemo(), DELAY, DELAY);

        // Sleep long enough to let the first timer finish
        try {
            Thread.sleep(DURATION*2);
        } catch (Exception e) {}
        
        // Start and run a fixed-rate timer
        timer = new Timer();
        startTime = prevTime = System.currentTimeMillis();
        System.out.println("Fixed Rate Times");
        timer.scheduleAtFixedRate(new UtilTimerDemo(), DELAY, DELAY);
    }
}

*original author: Chet Haase (former client architect for Java SE at Sun Microsystem, now work for Adobe)

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s