ROBERT BANDA
PROGRAMMING 2
UNIT3 ASSIGNMENT
The Clock class
Clock.java
import java.text.SimpleDateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class clock {
// Method to updating and printing the current time
public void displayTime(){
while (true){
Date currentTime= new Date();
SimpleDateFormat formatter = new sssss
String formattedTime = formatter.format(currentTime);
System.out.println("Current Time: " + formattedTime);
try {
Thread.sleep(2000); // sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The clock Threads
Clock app.java
public class ClockApp {
public static void main(String[] args) {
//example of a clock class
Clock clock = new Clock();
// create and start the clock display thread with higher priority
s displayTread.setPriority(Thread.MAX_PRIORITY);
displayTread.start();
// creating and start background updating thread with lower priority
Thread updateTread = new Thread(() -> {
while (true) {
// simulate background tasks or updates
try {
Thread.sleep(6000);// sleep for 6 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
updateTread.setPriority(Thread.MIN_PRIORITY);
updateTread.start();
}
}
Explanation
Imports.
Java.text.SimpleDateFormart: used to format the date and time string
Java.util.Date: Represent the current date and time.
TimeUpdateer Class:
An extension of Thread; This is responsible for continuously getting the
time and updating an internal variable with the formatted string.
Private currentTime: stores format current time string
Clockclass:This is the main class where program executes
In summary, this code effectively separate the time update logic from the
printing logic using two threads,making it more modular.
Error handling is implemented to catch InterruptedExceptions during the
thread sleeps,ensuring the the program behaves smooth fully even if
interrupted.
Reference:
Eck, D. J. (2022). Introduction to programming using java version 9, JavaFX
edition. Licensed Under CC 4.0. https://math.hws.edu/javanotes/