01: /**
02:    A stopwatch accumulates time when it is running. You can 
03:    repeatedly start and stop the stopwatch. You can use a
04:    stopwatch to measure the running time of a program.
05: */
06: public class StopWatch
07: {  
08:    /**
09:       Constructs a stopwatch that is in the stopped state
10:       and has no time accumulated.
11:    */
12:    public StopWatch()
13:    {  
14:       reset();
15:    }
16: 
17:    /**
18:       Starts the stopwatch. Time starts accumulating now.
19:    */
20:    public void start()
21:    {  
22:       if (isRunning) return;
23:       isRunning = true;
24:       startTime = System.currentTimeMillis();
25:    }
26:    
27:    /**
28:       Stops the stopwatch. Time stops accumulating and is
29:       is added to the elapsed time.
30:    */
31:    public void stop()
32:    {  
33:       if (!isRunning) return;
34:       isRunning = false;
35:       long endTime = System.currentTimeMillis();
36:       elapsedTime = elapsedTime + endTime - startTime;
37:    }
38:    
39:    /**
40:       Returns the total elapsed time.
41:       @return the total elapsed time
42:    */
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:    }
53:    
54:    /**
55:       Stops the watch and resets the elapsed time to 0.
56:    */
57:    public void reset()
58:    {  
59:       elapsedTime = 0;
60:       isRunning = false;
61:    }
62:    
63:    private long elapsedTime;
64:    private long startTime;
65:    private boolean isRunning;
66: }