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

Programming Assignment Unit 3

Uploaded by

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

Programming Assignment Unit 3

Uploaded by

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

Clock.

java
Code:
import java.text.SimpleDateFormat;
import java.util.Date;

public class Clock {


private volatile boolean running = true;

public static void main(String[] args) {


Clock clock = new Clock();
clock.startClock();
}

public void startClock() {


Thread timeUpdaterThread = new Thread(new TimeUpdater());
Thread timePrinterThread = new Thread(new TimePrinter());

// Set thread priorities


timeUpdaterThread.setPriority(Thread.MIN_PRIORITY); // Low priority
timePrinterThread.setPriority(Thread.MAX_PRIORITY); // High priority

timeUpdaterThread.start();
timePrinterThread.start();
}

private class TimeUpdater implements Runnable {


@Override
public void run() {
while (running) {
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

private class TimePrinter implements Runnable {


@Override
public void run() {
while (running) {
printCurrentTime();
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

private void printCurrentTime() {


SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss dd-MM-yyyy");
Date date = new Date();
System.out.println(formatter.format(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. timeUpdaterThread.setPriority(Thread.MIN_PRIORITY); sets the updater thread
to the lowest priority.
II. timePrinterThread.setPriority(Thread.MAX_PRIORITY); sets the printer thread
to the highest priority.
Screenshot:

You might also like