Clock.
java
Code:
import [Link];
import [Link];
public class Clock {
private volatile boolean running = true;
public static void main(String[] args) {
Clock clock = new Clock();
[Link]();
}
public void startClock() {
Thread timeUpdaterThread = new Thread(new TimeUpdater());
Thread timePrinterThread = new Thread(new TimePrinter());
// Set thread priorities
[Link](Thread.MIN_PRIORITY); // Low priority
[Link](Thread.MAX_PRIORITY); // High priority
[Link]();
[Link]();
}
private class TimeUpdater implements Runnable {
@Override
public void run() {
while (running) {
try {
[Link](1000); // Sleep for 1 second
} catch (InterruptedException e) {
[Link]();
}
}
}
}
private class TimePrinter implements Runnable {
@Override
public void run() {
while (running) {
printCurrentTime();
try {
[Link](1000); // Sleep for 1 second
} catch (InterruptedException e) {
[Link]();
}
}
}
private void printCurrentTime() {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss dd-MM-yyyy");
Date date = new Date();
[Link]([Link](date));
}
}
}
Explanation
1. Clock Class:
I. The Clock class contains the main logic for the application.
II. startClock method initializes and starts the threads for updating and printing the
time.
2. TimeUpdater Thread:
I. A background thread that simulates time updates (in this simple example, it just
sleeps for 1 second continuously).
II. This thread has a lower priority.
3. TimePrinter Thread:
I. A thread that prints the current time to the console every second.
II. This thread has a higher priority to ensure more precise time display.
4. Thread Priorities:
I. [Link](Thread.MIN_PRIORITY); sets the updater thread
to the lowest priority.
II. [Link](Thread.MAX_PRIORITY); sets the printer thread
to the highest priority.
Screenshot: