// StopwatchKL.java Copyright (c) 2005 Kari Laitinen // http://www.naturalprogramming.com // 2005-06-21 File created. // 2005-06-21 Last modification. // Solution to exercise 16-7 // This program may sometimes print some numbers to the screen // after the stopwatch has been stopped. I guess that the reason // for that behavior is that in those cases the stopping command // is given in the middle of a printing operation. import java.util.* ; class ThreadToMeasureTime extends Thread { boolean must_measure_time = true ; public void stop_this_thread() { must_measure_time = false ; } public void run() { long start_time_ticks, current_time_ticks ; long elapsed_milliseconds ; System.out.print( "\n" ) ; start_time_ticks = System.currentTimeMillis() ; while ( must_measure_time == true ) { current_time_ticks = System.currentTimeMillis() ; elapsed_milliseconds = ( current_time_ticks - start_time_ticks ) ; System.out.printf( "\r %d:%02d:%02d", elapsed_milliseconds / 60000, // minutes (( elapsed_milliseconds % 60000 ) / 1000 ), (( elapsed_milliseconds % 1000 ) / 10 ) ) ; try { Thread.sleep( 10 ) ; // Sleeping 0.01 seconds } catch ( InterruptedException caught_exception ) { } } } } class StopwatchKL { public static void main( String[] not_in_use ) { Scanner keyboard = new Scanner( System.in ) ; ThreadToMeasureTime thread_to_measure_time = new ThreadToMeasureTime() ; System.out.print( "\n Press the Enter key to start the stopwatch. " ) ; String any_string_from_keyboard = keyboard.nextLine() ; System.out.print( "\n Press the Enter key to stop the stopwatch.\n" ) ; thread_to_measure_time.start() ; any_string_from_keyboard = keyboard.nextLine() ; thread_to_measure_time.stop_this_thread() ; } }