// Clock.java (c) 2005 Kari Laitinen // http://www.naturalprogramming.com // 2004-09-26 File created. // 2005-05-15 Last modification. /* In this program the interrupt() method is used to stop the Thread.sleep() operations. In addition, the stop_this_thread() methods are called to ensure that the threads stop. It is likely that this program would work without the stop_this_thread() methods. */ import java.util.* ; class ThreadToShowSeconds extends Thread { boolean must_show_seconds = true ; public void stop_this_thread() { must_show_seconds = false ; } public void run() { while ( must_show_seconds == true ) { Calendar date_and_time_now = new GregorianCalendar() ; int seconds_of_current_time = date_and_time_now.get( Calendar.SECOND ) ; if ( ( seconds_of_current_time % 20 ) == 0 ) { System.out.print( "\n" ) ; } System.out.printf( " %02d", seconds_of_current_time ) ; try { Thread.sleep( 1000 ) ; // Delay of one second. } catch ( InterruptedException caught_exception ) { must_show_seconds = false ; } } } } class ThreadToShowFullTimeInfo extends Thread { boolean must_show_full_time_info = true ; public void stop_this_thread() { must_show_full_time_info = false ; } public void run() { Calendar date_and_time_now = new GregorianCalendar() ; int seconds_to_first_time_printing = 60 - date_and_time_now.get( Calendar.SECOND ) ; try { Thread.sleep( seconds_to_first_time_printing * 1000 ) ; } catch ( InterruptedException caught_exception ) { must_show_full_time_info = false ; } while ( must_show_full_time_info == true ) { date_and_time_now = new GregorianCalendar() ; System.out.printf( "\n\n %tT \n\n", date_and_time_now ) ; try { Thread.sleep( 60000 ) ; // Delay of 60 seconds. } catch ( InterruptedException caught_exception ) { must_show_full_time_info = false ; } } } } class Clock { public static void main( String[] not_in_use ) { Scanner keyboard = new Scanner( System.in ) ; ThreadToShowSeconds thread_to_show_seconds = new ThreadToShowSeconds() ; ThreadToShowFullTimeInfo thread_to_show_full_time_info = new ThreadToShowFullTimeInfo() ; System.out.print( "\n Press the Enter key to stop the clock.\n\n" ) ; thread_to_show_seconds.start() ; thread_to_show_full_time_info.start() ; String any_string_from_keyboard = keyboard.nextLine() ; thread_to_show_seconds.stop_this_thread() ; thread_to_show_full_time_info.stop_this_thread() ; thread_to_show_seconds.interrupt() ; thread_to_show_full_time_info.interrupt() ; } }