Programming2 Unit 3
Programming2 Unit 3
PROGRAMMING 2
UNIT3 ASSIGNMENT
Clock.java
import java.text.SimpleDateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class clock {
// Method to updating and printing the current time
public void displayTime(){
while (true){
Date currentTime= new Date();
SimpleDateFormat formatter = new sssss
String formattedTime = formatter.format(currentTime);
System.out.println("Current Time: " + formattedTime);
try {
Thread.sleep(2000); // sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Clock app.java
public class ClockApp {
public static void main(String[] args) {
//example of a clock class
Clock clock = new Clock();
// create and start the clock display thread with higher priority
s displayTread.setPriority(Thread.MAX_PRIORITY);
displayTread.start();
// creating and start background updating thread with lower priority
Thread updateTread = new Thread(() -> {
while (true) {
// simulate background tasks or updates
try {
Thread.sleep(6000);// sleep for 6 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
updateTread.setPriority(Thread.MIN_PRIORITY);
updateTread.start();
}
}
Explanation
Imports.
TimeUpdateer Class:
In summary, this code effectively separate the time update logic from the
printing logic using two threads,making it more modular.
Error handling is implemented to catch InterruptedExceptions during the
thread sleeps,ensuring the the program behaves smooth fully even if
interrupted.
Reference: