【问题标题】:Java StopWatch Suspend and Resume timer not workingJava 秒表挂起和恢复计时器不起作用
【发布时间】:2014-11-30 06:45:36
【问题描述】:

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

公共无效停止(){

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

【问题讨论】:

    标签: java stopwatch


    【解决方案1】:
    if(state == RUNNING){
        elaspedTime = System.currentTimeMillis() - startTime;
        state = RESUME;
    }
    

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

    在您的 resume 方法中将 RUNNING 更改为 SUSPENDED

    【讨论】:

    • 非常感谢。我已更改为暂停。现在,而不是 0 输出,它给了我 2300,我已经为 Thread.Sleep(2300).. 所以,我不知道我怎么能暂停程序说另外 2.3 秒并获得经过时间 4.6 秒(线程睡眠 2.3 + 暂停 2.3)?提前谢谢你。
    • 不客气,如果它回答了你的问题,请勾选我的答案旁边的复选标记。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2014-07-18
    • 2023-04-02
    • 2017-05-29
    • 2012-05-20
    • 2011-07-09
    • 1970-01-01
    相关资源
    最近更新 更多