Java StopWatch挂起和恢复计时器不工作

时间:2014-11-30 06:45:37

标签: java stopwatch

以下代码的目的是测试StopWatch的重置,启动,暂停和恢复。应该可以在给定时间点暂停秒表并在以后恢复。在这种情况下,经过时间是计时器最终停止时所有挂起和恢复事件的累计总数。如果我删除timer.suspend()和timer.resume(),代码工作正常。当我运行代码时,线程进入休眠状态2.3秒并在输出中给出经过时间2300。但是,使用suspend和resume方法,它会休眠2.3秒,但输出为0。

您能否建议/建议代码中有什么问题?

谢谢。

 interface StopWatch {

public void reset();
public void start();
public void stop();
public void suspend();
public void resume();
public long getElapsedTime();
public int getState();
public static final int RESET = 0, RUNNING =1, STOPPED =2, SUSPENDED = 3, RESUME = 0;}

计时器类

class Timer implements StopWatch{
private long startTime;
private long elaspedTime;
private int state;
public Timer(){reset();}

public void reset(){
    state = RESET;
    elaspedTime = 0;
}
public void start(){
    if(state==RESET){
        startTime = System.currentTimeMillis();
        state = RUNNING;
        }
}     

public void stop(){

    if(state == RUNNING){
        elaspedTime = System.currentTimeMillis() - startTime;
        state = STOPPED;
    }
}
public void suspend() {
    if(state == RUNNING){
        elaspedTime = System.currentTimeMillis() - startTime;
        state = SUSPENDED;
    }
}
public void resume(){

    if(state == RUNNING){
        elaspedTime = System.currentTimeMillis() - startTime;
        state = RESUME;
    }
}

public long getElapsedTime() {
    if(state == RUNNING){
        long elasped = System.currentTimeMillis() - startTime;
        return elasped;
    }
    else if (state == STOPPED)
        return elaspedTime;

    else if (state == RESUME)
        return elaspedTime;
    return 0;
}
public int getState(){
    return state;
}}

秒表测试

 public class StopWatchTest {
        public static  void main (String[] args){
        Timer timer = new Timer();
        timer.start();
        try{
            Thread.sleep(2300);
            timer.suspend();
            timer.resume();
        }catch (InterruptedException e){}
        timer.stop();
        long duration = timer.getElapsedTime();
        System.out.println(duration);
    }}

1 个答案:

答案 0 :(得分:0)

if(state == RUNNING){
    elaspedTime = System.currentTimeMillis() - startTime;
    state = RESUME;
}

resume方法中,您正在检查秒表是否正在运行,如何恢复已经运行的秒表?

RUNNING方法中将SUSPENDED更改为resume