Programming Assignment Unit 3:
This program, titled Simple Clock Application, demonstrates the implementation of Java's
multithreading capabilities to create a continuously updating clock that displays the current time
and date in a readable format (e.g., HH:mm:ss dd-MM-yyyy" ). The primary class, Clock, is
responsible for managing and displaying the time. It utilizes the SimpleDateFormat and Date
classes to format and fetch the current system time, ensuring that the output is presented in the
desired format.
The application implements two key threads: one for updating the time in the background and
another for printing the time to the console. The background thread continuously updates every
second, ensuring the clock is accurate, while the display thread prints the current time every
second for real-time user visibility. Both threads are configured with thread priorities, with the
display thread given a higher priority to ensure more precise and timely output, while the update
thread is assigned a lower priority since its task does not need to dominate processing resources.
Source code:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Clock {
// Method to get the current time in the required format
public static String getCurrentTime() {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss dd-
MM-yyyy");
Date date = new Date();
return formatter.format(date);
}
public static void main(String[] args) {
// Thread for continuously updating the time
Thread updateTimeThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
// Update time every second
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
// Thread for printing the time to the console
Thread displayTimeThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("Current Time: " +
Clock.getCurrentTime());
try {
// Print the time every second
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
// Setting thread priorities
updateTimeThread.setPriority(Thread.MIN_PRIORITY); // Background
thread with low priority
displayTimeThread.setPriority(Thread.MAX_PRIORITY); // Display
thread with high priority
// Start the threads
updateTimeThread.start();
displayTimeThread.start();
}
}
Output screenshot:
References:
References:
Gaddis, T. (2019). Starting Out with Java: From Control Structures through Objects (6th ed.).
Pearson.
Eck, D. J. (2022). Introduction to programming using Java: Version 9, Swing
edition. Hobart and William Smith Colleges.
W3Schools. (n.d.). Java tutorial. W3Schools. https://www.w3schools.com/java/