1 /** StopWatch.java 2 A stopwatch accumulates time when it is running. You can 3 repeatedly start and stop the stopwatch. You can use a 4 stopwatch to measure the running time of a program. */ 6 public class StopWatch 7 { 8 /** 9 Constructs a stopwatch that is in the stopped state 10 and has no time accumulated. */ 12 public StopWatch() 13 { 14 reset(); 15 } 17 /** 18 Starts the stopwatch. Time starts accumulating now. */ 20 public void start() 21 { 22 if (isRunning) return; 23 isRunning = true; 24 startTime = System.currentTimeMillis(); 25 } 27 /** 28 Stops the stopwatch. Time stops accumulating and is 29 is added to the elapsed time.*/ 31 public void stop() 32 { 33 if (!isRunning) return; 34 isRunning = false; 35 long endTime = System.currentTimeMillis(); 36 elapsedTime = elapsedTime + endTime - startTime; 37 } 39 /** 40 Returns the total elapsed time. 41 @return the total elapsed time*/ 43 public long getElapsedTime() 44 { 45 if (isRunning) 46 { 47 long endTime = System.currentTimeMillis(); 48 return elapsedTime + endTime - startTime; 49 } 50 else 51 return elapsedTime; 52 } 54 /** 55 Stops the watch and resets the elapsed time to 0.*/ 57 public void reset() 58 { 59 elapsedTime = 0; 60 isRunning = false; 61 } 63 private long elapsedTime; 64 private long startTime; 65 private boolean isRunning; 66 }