Bachelor of Computer Science, University of the People
CS 1103 Programming 2
Dr. Marc Augustin
May 1, 2024
package com.codewithMunyendo;
import java.text.SimpleDateFormat;
import java.util.Date;
class Clock {
// SimpleDateFormat to format the time and date
private SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss dd-
MM-yyyy");
// Method to display the current time and date
public void displayTime() {
while (true) {
// Get the current time and date
Date now = new Date();
// Format the time and date
String formattedTime = dateFormat.format(now);
// Print the formatted time and date to the console
System.out.println("Current time: " + formattedTime);
// Sleep for one second before updating
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
// Handle interruption
System.out.println("Display thread interrupted.");
}
}
}
}
class TimeUpdater implements Runnable {
// Clock instance
private Clock clock;
// Constructor
public TimeUpdater(Clock clock) {
this.clock = clock;
}
@Override
public void run() {
// Continuously update the time
while (true) {
// For now, just sleep to simulate time updates
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// Handle interruption
System.out.println("Updater thread interrupted.");
}
}
}
}
public class ClockApplication {
public static void main(String[] args) {
// Create a Clock instance
Clock clock = new Clock();
// Create a Thread for displaying the time
Thread displayThread = new Thread(() -> clock.displayTime());
// Set the thread priority higher for better timekeeping precision
displayThread.setPriority(Thread.MAX_PRIORITY);
// Create a TimeUpdater instance
TimeUpdater timeUpdater = new TimeUpdater(clock);
// Create a Thread for updating the time
Thread updateThread = new Thread(timeUpdater);
// Set the thread priority lower
updateThread.setPriority(Thread.MIN_PRIORITY);
// Start both threads
displayThread.start();
updateThread.start();
}
}
OUTPUT