Java loop for a certain duration

后端 未结 8 2135
花落未央
花落未央 2020-12-13 22:10

Is there a way I can do a for loop for a certain amount of time easily? (without measuring the time ourselves using System.currentTimeMillis() ?)

I.e. I want to do s

8条回答
  •  Happy的楠姐
    2020-12-13 22:19

    I made a simple, but sucky, implementation for this problem. I wanted to avoid Timer and TimeTask and ended up with this quickfix solution.

    The main idea is that I simply wanted to create an independed countdown timer which I could just start and call isFinished() to check if the countdown is finished.

    package RIPv3;
    
    /**
     * Creates a countdown timer which runs its own thread and uses CountdownTimerThread,                which runs yet another
     * thread.
     *
     * start() method is called to start the countdown.
     * isFinished() method is called to check if the countdown is finished or not.
     * 
     * ! Be Aware!
     * This is a quickfix and sucky implementation.
     * There will be a small delay. This is not accurate.
     * 
     * @author Endre Vestbø
     * @version 1.0 (09.05.2011)
     */
    public class CountdownTimer extends Thread {
    /* Countdown timer */
    private CountdownTimerThread timer;
    
    /**
     * Creates a new timer and sets time to count down
     * @param time
     *          Time to count down
     */
    public CountdownTimer(long time) {
        this.timer = new CountdownTimerThread(time);
    }
    
    public void run() {
        this.timer.start();
    }
    
    /**
     * @return
     *      False if timer is running, else true
     */
    public boolean isFinished() {
        if(this.timer.getState() == Thread.State.TERMINATED)
            return true;
    
        return false;
    }   
    }
    

     package RIPv3;
    
    /**
     * Used by CountdownTimer to count down time.
     * 
     * @author Endre Vestbø
     * @version 1.0  (09.05.2011)
     *
     */
    public class CountdownTimerThread extends Thread {
    private long time;
    
    /** Create a new timer */
    public CountdownTimerThread(long time) {
        this.time = time;
    }
    
    /**
     * Start a countdown
     * @param period
     *      Period to count down given in milliseconds
     */
    public void run() {
        try {
            sleep(this.time);
        } catch (InterruptedException e) {
    
        }
    }
    }
    

提交回复
热议问题