// AlarmclockKL.java Copyright (c) 2005 Kari Laitinen // http://www.naturalprogramming.com // 2005-06-21 File created. // 2005-06-21 Last modification. // This is a solution to Exercise 16-8. import java.util.* ; class ThreadToMeasureTimeAndAlarm extends Thread { int alarm_hour ; int alarm_minute ; boolean must_measure_time_and_alarm = true ; public ThreadToMeasureTimeAndAlarm( int given_alarm_hour, int given_alarm_minute ) { alarm_hour = given_alarm_hour ; alarm_minute = given_alarm_minute ; } public void stop_this_thread() { must_measure_time_and_alarm = false ; } public void run() { boolean it_is_time_to_give_alarm = false ; while ( must_measure_time_and_alarm == true && it_is_time_to_give_alarm == false ) { Calendar current_time = new GregorianCalendar() ; int current_hour = current_time.get( Calendar.HOUR_OF_DAY ) ; int current_minute = current_time.get( Calendar.MINUTE ) ; if ( current_hour == alarm_hour && current_minute == alarm_minute ) { it_is_time_to_give_alarm = true ; } System.out.printf( "\r Current time: %02d:%02d", current_hour, current_minute ) ; System.out.printf( " Alarm time: %02d:%02d", alarm_hour, alarm_minute ) ; try { Thread.sleep( 5000 ) ; // Check time once in every 5 seconds. } catch ( InterruptedException caught_exception ) { } } while ( must_measure_time_and_alarm == true ) { System.out.print( "\u0007" ) ; // Output the Alert sound 0x07 try { Thread.sleep( 1000 ) ; // Alert is given once a second. } catch ( InterruptedException caught_exception ) { } } } } class AlarmclockKL { public static void main( String[] not_in_use ) { Scanner keyboard = new Scanner( System.in ) ; System.out.print( "\n Give alarm hour between 0 ... 23 : " ) ; int alarm_hour = Integer.parseInt( keyboard.nextLine() ) ; System.out.print( "\n Give alarm minute between 0 ... 59 : " ) ; int alarm_minute = Integer.parseInt( keyboard.nextLine() ) ; System.out.print( "\n Press the Enter key to stop the alarm sound " + "\n or deactivate the alarm clock.\n\n" ) ; ThreadToMeasureTimeAndAlarm thread_to_measure_time_and_alarm = new ThreadToMeasureTimeAndAlarm( alarm_hour, alarm_minute ) ; thread_to_measure_time_and_alarm.start() ; String any_string_from_keyboard = keyboard.nextLine() ; thread_to_measure_time_and_alarm.stop_this_thread() ; } }