Simple Clock Application Assignment: Java Threads in Action
This assignment challenges you to create a simple clock application using Java threads. You'll
gain practical experience with the Java Thread model, understand multithreading concepts, and
explore thread priorities for task prioritization.
Scenario:
Develop a program that displays the current time and date continuously. Utilize Java threads to
handle time updates in the background and display them concurrently. Observe how thread
priorities impact timekeeping precision.
Requirements:
Clock Class:
• Create a Clock class responsible for displaying time and date in a readable format (e.g.,
"HH:mm:ss dd-MM-yyyy").
public class Clock {
private Date currentTime;
public Clock() {
currentTime = new Date();
}
public void update() {
currentTime = new Date();
}
public String getTimeString() {
SimpleDateFormat formatter = new
SimpleDateFormat("HH:mm:ss dd-MM-yyyy");
return formatter.format(currentTime);
}
}
• Implement a method to continuously update the current time.
public void run() {
while (true) {
update();
try {
Thread.sleep(1000); // Update every second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Thread Implementation:
• Use Java threads to achieve continuous time updates in the background.
public class ClockApplication {
public static void main(String[] args) {
Clock clock = new Clock();
Thread updateThread = new Thread(clock);
updateThread.start(); // Start the time update thread
Thread displayThread = new Thread(() -> {
while (true) {
try {
Thread.sleep(500); // Print every 500
milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(clock.getTimeString());
}
});
displayThread.start(); // Start the time display thread
}
}
• Implement a separate thread for printing the updated time to the console.
Thread Priorities:
• Introduce thread priorities for better timekeeping accuracy.
updateThread.setPriority(Thread.MAX_PRIORITY);
displayThread.setPriority(Thread.NORM_PRIORITY);
• Assign a higher priority to the clock display thread compared to the background update
thread.
Simulation Output:
• Continuously display the current time and date on the console.
14:23:15 15-02-2024
14:23:16 15-02-2024
14:23:17 15-02-2024
...
• Ensure time updates smoothly and accurately.