0% found this document useful (0 votes)
41 views11 pages

Java Thread-Based Clock Application

Uploaded by

Tornado Fair
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)
41 views11 pages

Java Thread-Based Clock Application

Uploaded by

Tornado Fair
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

1.

CS 1103-01 - AY2025-T2
2. Programming Assignment Unit 3

Programming Assignment Unit 3


Completion requirements
To do: Make a submission
Opened: Thursday, 28 November 2024, 12:05 AM
Due: Thursday, 5 December 2024, 11:55 PM

Assignment Title: Simple Clock Application

Through this assignment, you will gain knowledge and skills in understanding
the basics of the Java Thread model. You will also be able to gain your skills in
the implementation of multithreading concepts and the usage of thread
priorities for task prioritization in a real-life clock application.

Assignment Instructions

Scenario: You are tasked with developing a simple clock application that
utilizes Java threads to display the current time and date concurrently. This
project aims to explore the Java Thread model and its basics while illustrating
the use of threads and their priorities in a straightforward real-life scenario.

Requirements:

1. Clock Class:

a. Create a Clock class responsible for displaying the current time


and date.
b. Implement a method to continuously update and print the current
time.

2. Thread Implementation:

a. Utilize Java threads to ensure that the clock continuously updates


its time in the background.
b. Implement a separate thread for printing the time to the
console.

3. Thread Priorities:

a. Introduce thread priorities for better timekeeping precision.


b. The clock display thread should have a higher priority than the
background updating thread.

4. Simulation Output:

a. Display the current time and date in a readable format, e.g., "HH:mm:ss dd-
MM-yyyy".
b. Ensure that the clock continuously updates the time.

Guidelines

 Use meaningful variable and method names.


 Implement proper error handling where necessary.
 Ensure that your code is well-organized and follows Java coding
standards.
 Provide comments to explain the purpose of classes, methods, and any
complex logic.

Deliverables

1. Java Program Source Code:

a. Includes the Clock class and necessary threads.


b. Demonstrates the use of thread priorities for better precision.

2. Output Screenshot:

a. Provide a screenshot of the program's output, showcasing the continuously


updating clock with different thread priorities.

Grading Criteria

Your assignment will be evaluated based on the following criteria:

 Clock Class: The Clock class should accurately display the current time
and date. The method responsible for updating and printing the time
should work as expected. Use of meaningful variable and method
names, proper error handling, adherence to Java coding standards, and
well-organized code.
 Thread Implementation: Threads should be appropriately used to
ensure the clock continuously updates its time in the background. There
should be a separate thread for printing the time to the console. Ensure
proper synchronization and handling of concurrency issues. Threads
should work seamlessly without conflicts.
 Thread Priorities: Thread priorities should be introduced to achieve
better timekeeping precision. The clock display thread should have a
higher priority than the background updating thread.
 Readability and Continuity: The displayed time and date should be in a
readable format, and the clock should continuously update.
 Screenshot: Provide a screenshot of the program's output, showcasing
the continuously updating clock with different thread priorities.

The code :
import [Link];
import [Link];

class TimeUpdater extends Thread {


private String currentTime;
private boolean running = true;

public void run() {


while (running) {
// Get the current time
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss dd-MM-yyyy");
currentTime = [Link](new Date());
try {
[Link](1000); // Update every second
} catch (InterruptedException e) {
[Link]("TimeUpdater interrupted.");
running = false;
}
}
}

public String getCurrentTime() {


return currentTime;
}

public void stopUpdater() {


running = false;
}
}

class TimePrinter extends Thread {


private TimeUpdater timeUpdater;
public TimePrinter(TimeUpdater timeUpdater) {
[Link] = timeUpdater;
}

public void run() {


while (true) {
// Print the current time
[Link]("Current Time: " + [Link]());
try {
[Link](1000); // Print every second
} catch (InterruptedException e) {
[Link]("TimePrinter interrupted.");
break;
}
}
}
}

public class Clock {


public static void main(String[] args) {
TimeUpdater timeUpdater = new TimeUpdater();
TimePrinter timePrinter = new TimePrinter(timeUpdater);

[Link](Thread.MAX_PRIORITY); // Set higher priority for printing

[Link]();
[Link]();
// Stop the clock after 10 seconds for demonstration purpose
try {
[Link](10000);
} catch (InterruptedException e) {
[Link]();
}

[Link]();
[Link](); // Interrupt the time printing thread
}
}
--------------------------------------------------------------------------

Output:
The explanation:

Functionality:

This code creates a simple digital clock application in Java that prints the current time every
second to the console. It leverages two separate threads, TimeUpdater and TimePrinter, to
achieve this functionality.

Breakdown:

1- Imports:

[Link]: Used to format the date and time string.


[Link]: Represents the current date and time.

2- TimeUpdater Class:

An extension of Thread: This class is responsible for continuously getting the current time and
updating an internal variable with the formatted string.
private String currentTime: Stores the formatted current time string.
private boolean running: A flag to control the loop's execution.
run(): This method is executed when the TimeUpdater thread is started.
The while loop continues as long as running is true.
Inside the loop:
A SimpleDateFormat object with the desired date and time format ("HH:mm:ss dd-MM-yyyy")
is created.
The current date and time are obtained using new Date().
The currentTime variable is updated with the formatted time using [Link](new Date()).
The thread sleeps for 1 second ([Link](1000)) to ensure the time is updated every second.
If an InterruptedException occurs while sleeping, the loop exits, and running is set to false. This
indicates that the thread was interrupted.
getCurrentTime(): A public method that returns the current time stored in currentTime.
stopUpdater(): A public method that sets running to false, effectively stopping the loop in the
run() method and preventing further updates.
3- TimePrinter Class:

Another extension of Thread: This class is responsible for printing the current time retrieved
from the TimeUpdater to the console.
private TimeUpdater timeUpdater: A reference to the TimeUpdater object used to access the
current time.
TimePrinter(TimeUpdater timeUpdater): The constructor takes a TimeUpdater object as an
argument, which is stored in the timeUpdater variable.
run(): This method is executed when the TimePrinter thread is started.
The while loop runs indefinitely (or until interrupted).
Inside the loop:
The current time is retrieved by calling [Link]().
The time is printed to the console in the format "Current Time: [formatted time]".
The thread sleeps for 1 second ([Link](1000)) to ensure the time is printed every second.
If an InterruptedException occurs while sleeping, an error message is printed, and the loop exits.
4- Clock Class:
The main class where the program execution begins.
main(String[] args): The entry point of the program.
Creates a new TimeUpdater object.
Creates a new TimePrinter object, passing the TimeUpdater object as an argument.
Sets the priority of the TimePrinter thread to Thread.MAX_PRIORITY to give it higher priority
for smoother console output (optional optimization).
Starts both threads ([Link]() and [Link]()).
Sleeps the main thread for 10 seconds ([Link](10000)) to demonstrate the clock running
for a limited time.
Calls [Link]() to stop the time updates.
Interrupts the timePrinter thread using [Link](), prompting it to gracefully exit the
loop.

Key Points:

The code effectively separates the time update logic from the printing logic using two threads,
making it more modular.
Error handling is implemented to catch potential InterruptedExceptions during the thread sleeps,
ensuring the program behaves gracefully even if interrupted.
The Clock class demonstrates how to start, manage, and stop threads for a controlled execution.
The use of SimpleDateFormat allows customization of the time format.

Resources and References


1- Kirvan, P. (2022, May 26). What is multithreading?. WhatIs.
[Link]
%20is%20the%20ability%20of,program%20running%20on%20the%20computer.
2- SudhagarSudhagar 18811 gold badge33 silver badges1515 bronze badges, J.,
RalphChapinRalphChapin 3, Houcem BerrayanaHoucem Berrayana 3 kworrkworr 3, &
SARIKASARIKA 2722 bronze badges. (1957, July 1).

How exactly does multithreading work?. Stack Overflow.


[Link]

3- Geeks, G. for. (n.d.). The Physical Layer. Physical Layer in OSI Model.
[Link]

Common questions

Powered by AI

The Java clock application uses two separate threads, TimeUpdater and TimePrinter, to handle different tasks concurrently. The TimeUpdater thread continuously updates the current time by sleeping for one second and then updating a variable with the formatted current time . Simultaneously, the TimePrinter thread retrieves this updated time and prints it to the console every second . By separating these responsibilities into different threads, the program can efficiently update and display time without delays, thus improving performance and accuracy. Additionally, giving the TimePrinter thread a higher priority ensures smoother console output .

In the clock application, thread priorities are used to improve the precision of time display by giving the TimePrinter thread a higher priority than the TimeUpdater thread . This setup ensures that the visualization of time, which is critical for user experience, occurs more promptly compared to mere background time calculations. This prioritization is important to ensure that tasks crucial for real-time updates (like displaying time) are less likely to be delayed by other operations, thereby maintaining a seamless and accurate clock display .

The clock application implements error handling by catching InterruptedExceptions during the Thread.sleep() calls in both TimeUpdater and TimePrinter threads . If an interruption occurs, the TimeUpdater sets the running flag to false, effectively stopping time updates, while the TimePrinter prints an error message and breaks the loop. This prevents the threads from terminating unexpectedly and ensures the program can handle interruptions gracefully, contributing to its robustness and reliability .

Modular coding, which is exemplified in the clock application by separating responsibilities into different classes and threads, leads to better software development practices by increasing the maintainability and readability of the code . It allows developers to easily identify and modify specific functionalities without altering the entire system. This separation facilitates debugging and testing processes, as changes in one module do not affect others directly. It also encourages code reuse across different projects, improving efficiency and consistency in development .

Java's SimpleDateFormat enhances the application's functionality by allowing the customization of time and date formats for display . In this application, it formats the time to 'HH:mm:ss dd-MM-yyyy', making the display clear and readable to users. By providing a consistent and understandable format, it improves user experience by ensuring that the time and date are presented in a way that meets end-user expectations and requirements .

The demonstration setup of stopping the clock after 10 seconds helps in verifying the program's functionality within a controllable time frame . It showcases how the threads initiate, operate, and terminate, providing a quick execution cycle that allows for observation and validation of individual components and interactions. This limited run time aids users in assessing whether the clock updates and prints as desired, and if it handles interruptions properly, thus confirming the application's reliability .

Synchronization issues are avoided in the Java clock application by ensuring that the reading and updating of the current time occur in a controlled manner. The TimePrinter thread relies on the value updated by the TimeUpdater thread, which updates the currentTime once every second. Since these threads do not write to the same variable simultaneously and only one thread (TimeUpdater) modifies currentTime while the other (TimePrinter) reads it, the program avoids race conditions. Moreover, the logical separation of tasks limits direct interaction between threads, preventing concurrent updates that could lead to inconsistencies .

Separating time update logic from printing logic into different threads makes the program more modular and enhances its efficiency . This separation allows each thread to handle its specific task without interference, promoting clearer code structure and easier maintenance. By dividing responsibilities, each thread can operate concurrently, optimizing CPU utilization and ensuring smoother operation without one task blocking the other, which is crucial for applications requiring real-time updates like this clock application .

The setPriority method in Java is used to adjust the execution priorities of threads. In the clock application, it assigns a higher priority to the TimePrinter thread compared to the TimeUpdater thread . This prioritization is significant because it ensures that the console output, an observable action critical to user experience, is executed with minimal delay relative to other tasks. Thus, it effectively manages competing demands for CPU resources, helping maintain timely display operations .

The use of Java threads in this application illustrates the concept of concurrency by allowing separate tasks to run simultaneously. The TimeUpdater thread continuously updates the time in the background, while the TimePrinter thread fetches and displays this updated time concurrently . By operating independently, these threads enable the program to perform multiple operations at the same time, utilizing CPU resources more efficiently and improving the responsiveness of the application, which is a core aspect of concurrent programming .

You might also like