1  /**
  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.
  5  */
  6  public class StopWatch
  7  {  
  8     private long elapsedTime;
  9     private long startTime;
 10     private boolean isRunning;
 11  
 12     /**
 13        Constructs a stopwatch that is in the stopped state
 14        and has no time accumulated.
 15     */
 16     public StopWatch()
 17     {  
 18        reset();
 19     }
 20  
 21     /**
 22        Starts the stopwatch. Time starts accumulating now.
 23     */
 24     public void start()
 25     {  
 26        if (isRunning) return;
 27        isRunning = true;
 28        startTime = System.currentTimeMillis();
 29     }
 30     
 31     /**
 32        Stops the stopwatch. Time stops accumulating and is
 33        is added to the elapsed time.
 34     */
 35     public void stop()
 36     {  
 37        if (!isRunning) return;
 38        isRunning = false;
 39        long endTime = System.currentTimeMillis();
 40        elapsedTime = elapsedTime + endTime - startTime;
 41     }
 42     
 43     /**
 44        Returns the total elapsed time.
 45        @return the total elapsed time
 46     */
 47     public long getElapsedTime()
 48     {  
 49        if (isRunning) 
 50        {  
 51           long endTime = System.currentTimeMillis();
 52           return elapsedTime + endTime - startTime;
 53        }
 54        else
 55           return elapsedTime;
 56     }
 57     
 58     /**
 59        Stops the watch and resets the elapsed time to 0.
 60     */
 61     public void reset()
 62     {  
 63        elapsedTime = 0;
 64        isRunning = false;
 65     }
 66  }