以下代码的目的是测试StopWatch的复位,启动,挂起和恢复。应该有可能在给定的时间点暂停秒表,然后再恢复。在这种情况下,经过时间是当计时器最终停止时所有暂停和恢复事件的累积总数。如果我删除了timer.suspend()和timer.resume(),代码可以正常工作。当我运行代码时,线程进入睡眠状态达2.3秒,并在输出中给出经过的时间2300。但是,使用suspend and 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;
}
}
公共无效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);
}}
if(state == RUNNING){
elaspedTime = System.currentTimeMillis() - startTime;
state = RESUME;
}
在resume
您正在检查秒表是否正在运行的方法中,如何恢复已经运行的秒表?
更改RUNNING
为SUSPENDED
您的resume
方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句