implement DownloadWorker.java

This commit is contained in:
2026-06-08 00:36:38 +03:30
parent 1448d2184d
commit 015734784f
+47 -13
View File
@@ -1,4 +1,5 @@
import java.util.Random; import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/** /**
* Simulates downloading a single chunk of a file. * Simulates downloading a single chunk of a file.
@@ -11,33 +12,66 @@ public class DownloadWorker implements Runnable {
private final ChunkStatus chunkStatus; private final ChunkStatus chunkStatus;
private final DownloadConfig config; private final DownloadConfig config;
private final Random random;
public DownloadWorker(ChunkStatus chunkStatus, DownloadConfig config) { public DownloadWorker(ChunkStatus chunkStatus, DownloadConfig config) {
this.chunkStatus = chunkStatus; this.chunkStatus = chunkStatus;
this.config = config; this.config = config;
this.random = new Random();
} }
@Override @Override
public void run() { public void run() {
// TODO: Record the chunk start time in chunkStatus. long start = System.currentTimeMillis();
chunkStatus.setStartTimeMs(start);
double downloaded = 0.0; double downloaded = 0.0;
// TODO: Print a message that this chunk has started downloading. System.out.println(
"Chunk (id: " + chunkStatus.getChunkId() + ") has started downloading."
);
while (downloaded < chunkStatus.getChunkSizeMB()) { while (downloaded < chunkStatus.getChunkSizeMB()) {
// TODO: Generate a random sleep delay between min and max delay.
// TODO: Sleep for that delay. int randomSleepDelay = ThreadLocalRandom.current().nextInt(
// TODO: Generate a random download amount for this step. config.getMinStepDelayMs(),
// TODO: Increase downloaded, but do not go beyond chunk size. config.getMaxStepDelayMs() + 1
// TODO: Save the updated downloaded value into chunkStatus. );
// TODO: Optionally print step-by-step progress.
try {
Thread.sleep(randomSleepDelay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
double randomDownloadAmount = ThreadLocalRandom.current().nextDouble(
config.getMinStepDownloadMB(),
config.getMaxStepDownloadMB()
);
downloaded += randomDownloadAmount;
if (downloaded > chunkStatus.getChunkSizeMB()) {
downloaded = chunkStatus.getChunkSizeMB();
}
chunkStatus.setDownloadedMB(downloaded);
System.out.println(
"Chunk (id: " + chunkStatus.getChunkId() + ") progress: "
+ downloaded + " / "
+ chunkStatus.getChunkSizeMB() + " MB"
);
} }
// 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 end = System.currentTimeMillis();
chunkStatus.setEndTimeMs(end);
System.out.println(
"Chunk (id: " + chunkStatus.getChunkId() + ") has finished downloading. Took: "
+ chunkStatus.getDownloadDurationMs() + " ms"
);
} }
} }