Programming Assignment Unit 3
In this task, we were asked to create a simple clock program that talks continuously
and stops when you click Stop from the program itself. I will list the program below,
followed by pictures of the output, while the explanation will be inside the code itself
in the form of comments.
program:
//Import the package containing the class
import java.text.SimpleDateFormat;//SimpleDateFormat: Class
coordinates dates and times.
//Import the package that contains the Date class,
// which is a class that represents the current date and time.
import java.util.Date;
//Import the package that contains the TimeZone class,
// which is a class that represents time zones and sets the clock
time
import java.util.TimeZone;
public class Main {
// A function to continuously update and print the current time
public static void printCurrentTime() {
// Here the thread is created for background updates
Thread backgroundUpdater = new Thread(() -> {
while (true) {
try {
Thread.sleep(1000); // Sleep for 1 second
//Create a thread that continuously updates the
time in the background
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// // Create a thread that displays the current time
Thread displayTime = new Thread(() -> {
//Creates an object of the SimpleDateFormat class using
the specified style
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd-
MM-yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("GMT-5")); // Here
the required timezone is set
while (true) {
// Here the current time is displayed
System.out.println("Time: " + sdf.format(new
Date()));
/**Here this code is placed inside a try-catch block
to handle the InterruptedException exception as it can occur
when the thread execution is interrupted while
sleeping.
If executed, the exception trace will be printed
This is to facilitate error analysis and treatment.
*/
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Here thread priorities are set
backgroundUpdater.setPriority(Thread.MIN_PRIORITY); // Here
the background updater has low priority
displayTime.setPriority(Thread.MAX_PRIORITY); // Here the
priority of the presentation topic is high
// Start the threads
backgroundUpdater.start();
displayTime.start();
}
public static void main(String[] args) {
// Call the function to start the application
printCurrentTime();
}
}
Outputs:
Reference
Eck, D. J. (2022). Introduction to programming using Java, version 9. Hobart
and William Smith College. http://math.hws.edu/javanotes