Files
HW-08-Basic-Multithreading/src/main/java/DownloadWorker.java
T
2026-06-12 00:21:31 +03:30

64 lines
2.3 KiB
Java

import java.util.Random;
/**
* Simulates downloading a single chunk of a file.
*
* <p>This class is intentionally provided as a skeleton for students.
* The main multithreading and simulation logic should be completed
* in the run() method.</p>
*/
public class DownloadWorker implements Runnable {
private final ChunkStatus chunkStatus;
private final DownloadConfig config;
private final Random random;
public DownloadWorker(ChunkStatus chunkStatus, DownloadConfig config) {
this.chunkStatus = chunkStatus;
this.config = config;
this.random = new Random();
}
@Override
public void run() {
// TODO: Record the chunk start time in chunkStatus.
double downloaded = 0.0;
chunkStatus.setStartTimeMs(System.currentTimeMillis());
chunkStatus.setDownloadedMB(downloaded);
// TODO: Print a message that this chunk has started downloading.
System.out.println("Chunk #" + chunkStatus.getChunkId() + " started downloading.");
while (downloaded < chunkStatus.getChunkSizeMB()) {
// TODO: Generate a random sleep delay between min and max delay.
// TODO: Sleep for that delay.
// TODO: Generate a random download amount for this step.
// TODO: Increase downloaded, but do not go beyond chunk size.
// TODO: Save the updated downloaded value into chunkStatus.
// TODO: Optionally print step-by-step progress.
int delay = config.getMinStepDelayMs() + random.nextInt(config.getMaxStepDelayMs() - config.getMinStepDelayMs());
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
downloaded+=0.5;
if (downloaded > chunkStatus.getChunkSizeMB())
downloaded = chunkStatus.getChunkSizeMB();
chunkStatus.setDownloadedMB(downloaded);
}
// TODO: Mark the chunk as completed.
// TODO: Record the chunk end time in chunkStatus.
// TODO: Print a message that this chunk has finished downloading.
chunkStatus.setEndTimeMs(System.currentTimeMillis());
chunkStatus.setCompleted(true);
System.out.println("Chunk #" + chunkStatus.getChunkId() + " finished downloading.");
}
}