Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a41b6921a7 | ||
|
|
71517ef506 | ||
|
|
20f8f49c8e | ||
|
|
8d71e2814e |
@@ -0,0 +1,89 @@
|
|||||||
|
# Advanced Programing - 8 Report
|
||||||
|
|
||||||
|
## Theoretical Questions Answers
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. start() vs run()
|
||||||
|
### Output:
|
||||||
|
|
||||||
|
Calling run()
|
||||||
|
|
||||||
|
Running in: main
|
||||||
|
|
||||||
|
Calling start()
|
||||||
|
|
||||||
|
Running in: Thread-2
|
||||||
|
|
||||||
|
### Explanation
|
||||||
|
When calling "t1.run()" directly, the run method executes in the current thread (main).
|
||||||
|
When calling "t2.start()" , java creates a new thread and executes run() in that thread (Thread-2).
|
||||||
|
|
||||||
|
### Difference:
|
||||||
|
|
||||||
|
|start()|run()|
|
||||||
|
|-------|-----|
|
||||||
|
|Creates new thread|No new thread|
|
||||||
|
|Executes run() in new thread|Executed like nurmal method|
|
||||||
|
|Can only be called once|Can be called multiple times|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Deamon Threads
|
||||||
|
|
||||||
|
### Output(with demon):
|
||||||
|
|
||||||
|
Main thread ends
|
||||||
|
|
||||||
|
Deamon thread running...
|
||||||
|
|
||||||
|
(Program terminates quickly)
|
||||||
|
|
||||||
|
### Output(without demon):
|
||||||
|
|
||||||
|
Main thread ends.
|
||||||
|
|
||||||
|
Deamon thread running...
|
||||||
|
|
||||||
|
(20 times)
|
||||||
|
|
||||||
|
### Explanation
|
||||||
|
A daemon thread is a background thread that does NOT prevent the JVM from exiting.
|
||||||
|
When the main thread (non-daemon) finishes,
|
||||||
|
the JVM checks if there are any non-daemon threads still running.
|
||||||
|
Since only the daemon thread remains,
|
||||||
|
the JVM terminates immediately without waiting for the daemon thread to complete its 20 iterations.
|
||||||
|
|
||||||
|
Without setDaemon(true), the thread becomes a user thread (non-daemon) .
|
||||||
|
User threads prevent the JVM from exiting until they complete.
|
||||||
|
Therefore, the JVM waits for the thread to finish all 20 iterations before terminating the program.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Real-life use cases:
|
||||||
|
1. Garbage Collector (GC)
|
||||||
|
2. Auto-save features
|
||||||
|
3. Background logging
|
||||||
|
4. Session cleanup in web servers
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Lambda Expressions
|
||||||
|
|
||||||
|
### Output:
|
||||||
|
|
||||||
|
Thread is running using a...!
|
||||||
|
|
||||||
|
### What is `() -> {}`?
|
||||||
|
This is a **Lambda Expression** introduced in Java.
|
||||||
|
|
||||||
|
|
||||||
|
### Comparison:
|
||||||
|
|
||||||
|
| Traditional | Lambda |
|
||||||
|
|-------------|--------|
|
||||||
|
| Needs separate class | No separate class |
|
||||||
|
| More code | Concise |
|
||||||
|
| `new Thread(new Runnable(){...})` | `new Thread(() -> {...})` |
|
||||||
|
|
||||||
|
---
|
||||||
@@ -21,23 +21,42 @@ public class DownloadWorker implements Runnable {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// TODO: Record the chunk start time in chunkStatus.
|
long startTime = System.currentTimeMillis();
|
||||||
double downloaded = 0.0;
|
chunkStatus.setStartTimeMs(startTime);
|
||||||
|
|
||||||
// TODO: Print a message that this chunk has started downloading.
|
double downloaded = 0.0;
|
||||||
|
int chunkId = chunkStatus.getChunkId();
|
||||||
|
double chunkSize = chunkStatus.getChunkSizeMB();
|
||||||
|
|
||||||
|
System.out.println("[ Worker - " + chunkId +" ] Started downloading chunk " + chunkId +" (" + chunkSize + ") ");
|
||||||
|
|
||||||
while (downloaded < chunkStatus.getChunkSizeMB()) {
|
while (downloaded < chunkStatus.getChunkSizeMB()) {
|
||||||
// TODO: Generate a random sleep delay between min and max delay.
|
int delayMs = config.getMinStepDelayMs() + random.nextInt(config.getMaxStepDelayMs()-config.getMinStepDelayMs()+1);
|
||||||
// TODO: Sleep for that delay.
|
|
||||||
// TODO: Generate a random download amount for this step.
|
try {
|
||||||
// TODO: Increase downloaded, but do not go beyond chunk size.
|
Thread.sleep(delayMs);
|
||||||
// TODO: Save the updated downloaded value into chunkStatus.
|
}catch (InterruptedException e){
|
||||||
// TODO: Optionally print step-by-step progress.
|
System.out.println("[ Worker - " + chunkId +" ] interrupted ");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
double stepSize = config.getMinStepDownloadMB() + random.nextDouble() * (config.getMaxStepDownloadMB() - config.getMinStepDownloadMB());
|
||||||
|
|
||||||
|
downloaded = Math.min(chunkSize, downloaded + stepSize);
|
||||||
|
|
||||||
|
chunkStatus.setDownloadedMB(downloaded);
|
||||||
|
|
||||||
|
System.out.println("[ Worker - " + chunkId +" ] Chunk " + chunkId + ": " + Math.round(downloaded*10)/10.0 + "/" + chunkSize + "(" + Math.round((downloaded/chunkSize)*1000)/10.0 + ")");
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Mark the chunk as completed.
|
chunkStatus.setCompleted(true);
|
||||||
// TODO: Record the chunk end time in chunkStatus.
|
|
||||||
// TODO: Print a message that this chunk has finished downloading.
|
long endTime = System.currentTimeMillis();
|
||||||
|
chunkStatus.setEndTimeMs(endTime);
|
||||||
|
|
||||||
|
long duration = endTime - startTime;
|
||||||
|
|
||||||
|
System.out.println("[ Worker - " + chunkId +" ]Finished downloading chunk " + chunkId + "in" + (duration/1000.0) + "seconds");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-23
@@ -33,46 +33,39 @@ public class Main {
|
|||||||
Thread workerThread = new Thread(worker, "Worker-" + chunk.getChunkId());
|
Thread workerThread = new Thread(worker, "Worker-" + chunk.getChunkId());
|
||||||
|
|
||||||
workerThreads.add(workerThread);
|
workerThreads.add(workerThread);
|
||||||
|
System.out.println("Assigned chunk " + chunk.getChunkId() + "to thread: " + workerThread.getName());
|
||||||
// TODO:
|
|
||||||
// Students may print helpful debug information here,
|
|
||||||
// for example which chunk is assigned to which worker thread.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Create and start monitor thread
|
// 4. Create and start monitor thread
|
||||||
ProgressMonitor monitor = new ProgressMonitor(config, chunks);
|
ProgressMonitor monitor = new ProgressMonitor(config, chunks);
|
||||||
Thread monitorThread = new Thread(monitor, "Progress-Monitor");
|
Thread monitorThread = new Thread(monitor, "Progress-Monitor");
|
||||||
|
|
||||||
// TODO:
|
monitorThread.start();
|
||||||
// Start the monitor thread before starting the workers
|
|
||||||
// so that progress can be displayed while downloading happens.
|
|
||||||
//
|
|
||||||
// Example idea:
|
|
||||||
// monitorThread.start();
|
|
||||||
|
|
||||||
// 5. Start worker threads
|
// 5. Start worker threads
|
||||||
// TODO:
|
for (Thread thread : workerThreads){
|
||||||
// Start each worker thread in workerThreads.
|
thread.start();
|
||||||
// Use a loop and call start() on each thread.
|
}
|
||||||
|
|
||||||
// 6. Wait for workers to finish
|
// 6. Wait for workers to finish
|
||||||
// TODO:
|
for (Thread thread : workerThreads) {
|
||||||
// Wait for all worker threads to complete by calling join().
|
try{
|
||||||
// This should be done inside a try-catch block for InterruptedException.
|
thread.join();
|
||||||
//
|
}catch (InterruptedException e){
|
||||||
// Hint:
|
System.out.println("Main thread interrupted while waiting for" + thread.getName());}
|
||||||
// for (Thread thread : workerThreads) {
|
}
|
||||||
// thread.join();
|
|
||||||
// }
|
|
||||||
|
|
||||||
// TODO:
|
|
||||||
// After all workers finish, the monitor thread may also need to stop.
|
// After all workers finish, the monitor thread may also need to stop.
|
||||||
// Depending on how ProgressMonitor is implemented, students may:
|
// Depending on how ProgressMonitor is implemented, students may:
|
||||||
// - wait for it to finish on its own, or
|
// - wait for it to finish on its own, or
|
||||||
// - add a stopping mechanism in ProgressMonitor later.
|
// - add a stopping mechanism in ProgressMonitor later.
|
||||||
//
|
//
|
||||||
// If your monitor finishes automatically, you may join it here.
|
// If your monitor finishes automatically, you may join it here.
|
||||||
|
try{
|
||||||
|
monitorThread.join();
|
||||||
|
}catch (InterruptedException e){
|
||||||
|
System.out.println("Main thread interrupted while waiting for monitor");
|
||||||
|
}
|
||||||
// NOTE:
|
// NOTE:
|
||||||
// this final report may show 0 progress because no worker has actually run yet.
|
// this final report may show 0 progress because no worker has actually run yet.
|
||||||
// Until students complete the thread start/join TODOs above,
|
// Until students complete the thread start/join TODOs above,
|
||||||
|
|||||||
@@ -6,17 +6,21 @@ public class ProgressMonitor implements Runnable {
|
|||||||
private final int totalSizeMB;
|
private final int totalSizeMB;
|
||||||
private final List<ChunkStatus> chunks;
|
private final List<ChunkStatus> chunks;
|
||||||
private final long monitorDelayMs;
|
private final long monitorDelayMs;
|
||||||
|
private double previousTotalDownloadedMB;
|
||||||
|
private long previousTimeMs;
|
||||||
|
|
||||||
|
|
||||||
public ProgressMonitor(DownloadConfig config, List<ChunkStatus> chunks) {
|
public ProgressMonitor(DownloadConfig config, List<ChunkStatus> chunks) {
|
||||||
this.fileName = config.getFileName();
|
this.fileName = config.getFileName();
|
||||||
this.totalSizeMB = config.getTotalSizeMB();
|
this.totalSizeMB = config.getTotalSizeMB();
|
||||||
this.chunks = chunks;
|
this.chunks = chunks;
|
||||||
this.monitorDelayMs = 500;
|
this.monitorDelayMs = 500;
|
||||||
|
this.previousTotalDownloadedMB = 0.0;
|
||||||
|
this.previousTimeMs = System.currentTimeMillis();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// TODO:
|
|
||||||
// Repeatedly check chunk progress until all chunks are completed.
|
// Repeatedly check chunk progress until all chunks are completed.
|
||||||
// In each loop:
|
// In each loop:
|
||||||
// 1. Read the downloaded size from every chunk
|
// 1. Read the downloaded size from every chunk
|
||||||
@@ -24,9 +28,7 @@ public class ProgressMonitor implements Runnable {
|
|||||||
// 3. Count completed chunks
|
// 3. Count completed chunks
|
||||||
// 4. Print a progress message
|
// 4. Print a progress message
|
||||||
// 5. If completedChunks == chunks.size(), print a final monitor message and stop
|
// 5. If completedChunks == chunks.size(), print a final monitor message and stop
|
||||||
// 6. Otherwise sleep for monitorDelayMs and continue
|
// 6. Otherwise, sleep for monitorDelayMs and continue
|
||||||
|
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
double totalDownloadedMB = 0.0;
|
double totalDownloadedMB = 0.0;
|
||||||
int completedChunks = 0;
|
int completedChunks = 0;
|
||||||
@@ -44,19 +46,56 @@ public class ProgressMonitor implements Runnable {
|
|||||||
percent = (totalDownloadedMB * 100.0) / totalSizeMB;
|
percent = (totalDownloadedMB * 100.0) / totalSizeMB;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
long currentTimeMs = System.currentTimeMillis();
|
||||||
|
long timeDiffMs = currentTimeMs - previousTimeMs;
|
||||||
|
double downloadedDiff = totalDownloadedMB - previousTotalDownloadedMB;
|
||||||
|
|
||||||
|
double speedMBps = 0.0;
|
||||||
|
if (timeDiffMs > 0){
|
||||||
|
speedMBps = (downloadedDiff * 1000.0) / timeDiffMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
double etaSeconds = 0.0;
|
||||||
|
if (speedMBps > 0 && totalDownloadedMB < totalSizeMB){
|
||||||
|
double remainingMB =totalSizeMB - totalDownloadedMB;
|
||||||
|
etaSeconds = remainingMB / speedMBps;
|
||||||
|
}
|
||||||
|
|
||||||
|
previousTotalDownloadedMB = totalDownloadedMB;
|
||||||
|
previousTimeMs = currentTimeMs;
|
||||||
|
|
||||||
|
|
||||||
|
int barWidth = 50;
|
||||||
|
int filledWidth = (int)(barWidth * percent / 100.0);
|
||||||
|
|
||||||
|
System.out.print("[");
|
||||||
|
for (int i = 0; i < barWidth; i++) {
|
||||||
|
if (i < filledWidth){
|
||||||
|
System.out.print("=");
|
||||||
|
}else if (i == filledWidth && percent< 100){
|
||||||
|
System.out.print(">");
|
||||||
|
}else {
|
||||||
|
System.out.print(" ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
System.out.print("]");
|
||||||
|
|
||||||
System.out.printf(
|
System.out.printf(
|
||||||
"Progress for %s: %.1f/%.1f MB (%.2f%%), completed chunks: %d/%d%n",
|
"Progress for %s: %.1f/%.1f MB (%.2f%%), completed chunks: %d/%d%n , ETA: %s",
|
||||||
fileName,
|
fileName,
|
||||||
totalDownloadedMB,
|
totalDownloadedMB,
|
||||||
(double) totalSizeMB,
|
(double) totalSizeMB,
|
||||||
percent,
|
percent,
|
||||||
completedChunks,
|
completedChunks,
|
||||||
chunks.size()
|
chunks.size(),
|
||||||
|
speedMBps,
|
||||||
|
formatETA(etaSeconds)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (completedChunks == chunks.size()){
|
||||||
// TODO:
|
System.out.println("All chunks have been downloaded successfully!");
|
||||||
// If all chunks are completed, print a final message and exit the loop
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Thread.sleep(monitorDelayMs);
|
Thread.sleep(monitorDelayMs);
|
||||||
@@ -66,4 +105,20 @@ public class ProgressMonitor implements Runnable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private String formatETA(double etaSeconds){
|
||||||
|
if (etaSeconds <= 0){
|
||||||
|
return "Calculating ...";
|
||||||
|
}
|
||||||
|
int hours = (int)(etaSeconds/3600);
|
||||||
|
int minutes = (int)((etaSeconds%3600)/60);
|
||||||
|
int secondes = (int)(etaSeconds %60);
|
||||||
|
|
||||||
|
if (hours > 0){
|
||||||
|
return String.format("%dh %dm %ds" , hours, minutes, secondes);
|
||||||
|
}else if(minutes > 0){
|
||||||
|
return String.format("%dm %ds" , minutes, secondes);
|
||||||
|
}else{
|
||||||
|
return String.format("%ds", secondes);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user