0% found this document useful (0 votes)
30 views3 pages

Java Threaded Electronic Watch

The document presents a Java program that implements a simple clock application using multithreading. It includes a Clock class that displays the current time and date, and a TimeUpdater class that simulates time updates. The main method initializes and starts two threads for displaying and updating the time concurrently.

Uploaded by

munyendoadam9
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views3 pages

Java Threaded Electronic Watch

The document presents a Java program that implements a simple clock application using multithreading. It includes a Clock class that displays the current time and date, and a TimeUpdater class that simulates time updates. The main method initializes and starts two threads for displaying and updating the time concurrently.

Uploaded by

munyendoadam9
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Bachelor of Computer Science, University of the People

CS 1103 Programming 2

Dr. Marc Augustin

May 1, 2024
package [Link];

import [Link];
import [Link];

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 = [Link](now);
// Print the formatted time and date to the console
[Link]("Current time: " + formattedTime);
// Sleep for one second before updating
try {
[Link](1500);
} catch (InterruptedException e) {
// Handle interruption
[Link]("Display thread interrupted.");
}
}
}
}

class TimeUpdater implements Runnable {


// Clock instance
private Clock clock;

// Constructor
public TimeUpdater(Clock clock) {
[Link] = clock;
}

@Override
public void run() {
// Continuously update the time
while (true) {
// For now, just sleep to simulate time updates
try {
[Link](500);
} catch (InterruptedException e) {
// Handle interruption
[Link]("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(() -> [Link]());
// Set the thread priority higher for better timekeeping precision
[Link](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
[Link](Thread.MIN_PRIORITY);

// Start both threads


[Link]();
[Link]();
}
}

OUTPUT

Common questions

Powered by AI

Interrupt handling within the `Clock` and `TimeUpdater` classes enhances application robustness by providing a way to manage and gracefully handle interruptions from external signals during thread execution, such as system shutdown requests or attempts to stop the application. In the `displayTime` and `run` methods of both classes, `InterruptedException` is caught, ensuring that if a thread is interrupted, the program can log an appropriate message and potentially perform cleanup operations without crashing unexpectedly or leaving resources in an inconsistent state. This design increases the application's resilience against unexpected failures and enhances its ability to terminate smoothly .

Separating time display and time updating into two distinct classes, `Clock` and `TimeUpdater`, enhances modularity by clearly defining separate responsibilities for each class. This separation allows individual changes to the implementation of time display or time updating without affecting the other component. If, for instance, the way time is formatted or updated changes, only the corresponding class needs to be modified. This approach follows the single responsibility principle, a core tenet of modular software design, making the application easier to understand, test, and maintain. Furthermore, it enhances reusable code segments in the program, should similar functionalities be needed elsewhere .

The `TimeUpdater` class is designed to implement the `Runnable` interface rather than extending `Thread` because this approach provides greater flexibility in class design. By implementing `Runnable`, the `TimeUpdater` class does not inherit from `Thread`, allowing it to subclass from other classes if needed, adhering to Java's single inheritance model. This design also separates task execution from thread management, allowing for greater decoupling of thread execution logic from the task being performed. Utilizing `Runnable` promotes cleaner code organization and allows the task represented by `TimeUpdater` to be reused or executed by different threads without modification .

The `SimpleDateFormat` class in the `Clock` class is used to format the date and time into a human-readable string based on the specified pattern 'HH:mm:ss dd-MM-yyyy'. This class is crucial for converting the raw `Date` object into a format suitable for display in the console. Without using `SimpleDateFormat`, the time and date information would be presented in a less readable or non-customized manner, reducing the program's user-friendliness and required functionality, as correctly formatted time and date display is a central feature of the `Clock` class .

The `ClockApplication` uses two separate threads for display (`displayThread`) and update (`updateThread`) operations to handle these actions concurrently. This design allows the application to concurrently render the current time while potentially updating or processing additional tasks related to time. By segregating the concerns into different threads, the application can be more responsive and efficient, keeping time display accurate without being delayed by update calculations or processing. This approach addresses common concurrency challenges such as race conditions, uneven resource allocation, and ensuring timely execution of critical tasks like real-time display, which might be affected if handled within a single-threaded process .

Setting the display thread to maximum priority and the update thread to minimum priority ensures the display thread executes its tasks with precedence over the updating tasks, leading to more frequent and potentially more precise time displays. This configuration is beneficial when precise time display is critical. However, it may negatively impact the updating process's responsiveness and execution opportunities, potentially delaying non-critical updates performed by the update thread if the CPU is under heavy load. Balancing thread priorities is key to optimizing both display precision and update responsiveness, dependent on the application's specific requirements .

The infinite loop in the `Clock` class's `displayTime` method could lead to resource exhaustion, such as too high CPU load or memory leaks if not properly managed. The method continuously checks and prints the current time without any mechanism to stop the loop, which could prevent the application from terminating gracefully. To address these issues, a mechanism to exit the loop gracefully could be implemented, such as checking a shared interrupt flag or using a timer that periodically assesses whether the thread should continue execution. Incorporating these changes would allow for better resource management and application control .

In the `Clock` class, calling `Thread.sleep(1500)` within the `displayTime` method pauses the thread for 1.5 seconds after each time display cycle, reducing CPU usage by allowing the thread to be inactive during this period. Similarly, in the `TimeUpdater` class, calling `Thread.sleep(500)` causes the thread to sleep for 0.5 seconds, further conserving CPU resources by not performing operations continuously. However, these delays could affect application responsiveness if different time intervals for updates and displays are needed, making it important to fine-tune these sleep durations based on desired performance characteristics and precision requirements .

The `ClockApplication` program manages time display and updating concurrently by utilizing two separate threads. The `displayThread` is responsible for continuously printing the current time using the `Clock` class's `displayTime` method, while the `updateThread` simulates time updates using the `TimeUpdater` class, though it currently only sleeps without performing any real updates. The `displayThread` is given a maximum priority (`Thread.MAX_PRIORITY`) to ensure it executes with higher precedence, improving timekeeping precision, while the `updateThread` is assigned a minimum priority (`Thread.MIN_PRIORITY`) since it doesn't perform critical tasks in the current implementation. This setup prioritizes accurate and timely display of the current time on the console .

The `ClockApplication` demonstrates several design principles that help manage complexity in multi-threaded applications. Firstly, it applies the separation of concerns by isolating the time display logic from the updating logic, promoting modularity. Utilizing the `Runnable` interface instead of extending `Thread` enables clean separation between the task and its execution mechanism, allowing flexibility in managing thread behavior. Furthermore, setting different priorities for threads exemplifies managing resource allocation based on task importance. Finally, implementing thread-safe mechanisms, such as interrupt handling, assures that threads can terminate gracefully under certain conditions, enhancing the robustness and reliability of the application .

You might also like