Files
HW-08-Basic-Multithreading/src/main/java/ProgressMonitor.java
T
2026-06-24 18:53:41 +03:30

74 lines
2.3 KiB
Java

import java.util.List;
public class ProgressMonitor implements Runnable {
private final String fileName;
private final int totalSizeMB;
private final List<ChunkStatus> chunks;
private final long monitorDelayMs;
public ProgressMonitor(DownloadConfig config, List<ChunkStatus> chunks) {
this.fileName = config.getFileName();
this.totalSizeMB = config.getTotalSizeMB();
this.chunks = chunks;
this.monitorDelayMs = 500;
}
@Override
public void run() {
// TODO:
// Repeatedly check chunk progress until all chunks are completed.
// In each loop:
// 1. Read the downloaded size from every chunk
// 2. Add all downloaded amounts to totalDownloadedMB
// 3. Count completed chunks
// 4. Print a progress message
// 5. If completedChunks == chunks.size(), print a final monitor message and stop
// 6. Otherwise sleep for monitorDelayMs and continue
while (true) {
double totalDownloadedMB = 0.0;
int completedChunks = 0;
for (ChunkStatus chunk : chunks) {
totalDownloadedMB += chunk.getDownloadedMB();
if (chunk.isCompleted()) {
completedChunks++;
}
}
double percent = 0.0;
if (totalSizeMB > 0) {
percent = (totalDownloadedMB * 100.0) / totalSizeMB;
}
System.out.printf(
"Progress for %s: %.1f/%.1f MB (%.2f%%), completed chunks: %d/%d%n",
fileName,
totalDownloadedMB,
(double) totalSizeMB,
percent,
completedChunks,
chunks.size()
);
// TODO:
// If all chunks are completed, print a final message and exit the loop
if (completedChunks == chunks.size()){
System.out.println("All cchunks have been downloadeed.Monitor stopped.");
break;
}
try {
Thread.sleep(monitorDelayMs);
} catch (InterruptedException e) {
System.out.println("Progress monitor interrupted.");
return;
}
}
}
}