【发布时间】: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);
}}
【问题讨论】: