Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Programming Assignment Unit 3

Uploaded by

Tornado Fair
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Programming Assignment Unit 3

Uploaded by

Tornado Fair
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

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 java.text.SimpleDateFormat;
import java.util.Date;

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 = formatter.format(new Date());
try {
Thread.sleep(1000); // Update every second
} catch (InterruptedException e) {
System.out.println("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) {
this.timeUpdater = timeUpdater;
}

public void run() {


while (true) {
// Print the current time
System.out.println("Current Time: " + timeUpdater.getCurrentTime());
try {
Thread.sleep(1000); // Print every second
} catch (InterruptedException e) {
System.out.println("TimePrinter interrupted.");
break;
}
}
}
}

public class Clock {


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

timePrinter.setPriority(Thread.MAX_PRIORITY); // Set higher priority for printing

timeUpdater.start();
timePrinter.start();
// Stop the clock after 10 seconds for demonstration purpose
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}

timeUpdater.stopUpdater();
timePrinter.interrupt(); // 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:

java.text.SimpleDateFormat: Used to format the date and time string.


java.util.Date: 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 formatter.format(new Date()).
The thread sleeps for 1 second (Thread.sleep(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 timeUpdater.getCurrentTime().
The time is printed to the console in the format "Current Time: [formatted time]".
The thread sleeps for 1 second (Thread.sleep(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 (timeUpdater.start() and timePrinter.start()).
Sleeps the main thread for 10 seconds (Thread.sleep(10000)) to demonstrate the clock running
for a limited time.
Calls timeUpdater.stopUpdater() to stop the time updates.
Interrupts the timePrinter thread using timePrinter.interrupt(), 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.
https://www.techtarget.com/whatis/definition/multithreading#:~:text=Multithreading
%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.


https://stackoverflow.com/questions/10951124/how-exactly-does-multithreading-work

3- Geeks, G. for. (n.d.). The Physical Layer. Physical Layer in OSI Model.
https://aws.amazon.com/what-is/osi-model/

You might also like