首页 文章

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

提问于
浏览
0

下面代码的目的是测试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
    if(state == RUNNING){
        elaspedTime = System.currentTimeMillis() - startTime;
        state = RESUME;
    }
    

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

    resume 方法中将 RUNNING 更改为 SUSPENDED .

相关问题