// Clock.kt (c) Kari Laitinen // http://www.naturalprogramming.com // 2023-01-12 File created. /* 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.time.LocalDateTime class ThreadToShowSeconds : Thread() { var must_show_seconds = true fun stop_this_thread() { must_show_seconds = false } override fun run() { while ( must_show_seconds == true ) { val date_and_time_now = LocalDateTime.now() val seconds_of_current_time = date_and_time_now.getSecond() if ( ( seconds_of_current_time % 20 ) == 0 ) { print( "\n" ) } print( String.format( " %02d", seconds_of_current_time ) ) try { Thread.sleep( 1000 ) // Delay of one second. } catch ( caught_exception : InterruptedException ) { must_show_seconds = false } } } } class ThreadToShowFullTimeInfo : Thread() { var must_show_full_time_info = true fun stop_this_thread() { must_show_full_time_info = false } override fun run() { var date_and_time_now = LocalDateTime.now() val seconds_to_first_time_printing = 60 - date_and_time_now.getSecond() try { Thread.sleep( ( seconds_to_first_time_printing * 1000 ).toLong() ) } catch ( caught_exception : InterruptedException ) { must_show_full_time_info = false } while ( must_show_full_time_info == true ) { date_and_time_now = LocalDateTime.now() print( String.format( "\n\n %tT \n\n", date_and_time_now ) ) try { Thread.sleep( 60000 ) // Delay of 60 seconds. } catch ( caught_exception : InterruptedException ) { must_show_full_time_info = false } } } } fun main() { val thread_to_show_seconds = ThreadToShowSeconds() val thread_to_show_full_time_info = ThreadToShowFullTimeInfo() print( "\n Press the Enter key to stop the clock.\n\n" ) thread_to_show_seconds.start() thread_to_show_full_time_info.start() val any_string_from_keyboard = readLine()!! 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() }