diff --git a/src/main/java/DownloadWorker.java b/src/main/java/DownloadWorker.java index 546de2d..573f354 100644 --- a/src/main/java/DownloadWorker.java +++ b/src/main/java/DownloadWorker.java @@ -1,12 +1,5 @@ import java.util.Random; -/** - * Simulates downloading a single chunk of a file. - * - *
This class is intentionally provided as a skeleton for students. - * The main multithreading and simulation logic should be completed - * in the run() method.
- */ public class DownloadWorker implements Runnable { private final ChunkStatus chunkStatus; @@ -21,23 +14,31 @@ public class DownloadWorker implements Runnable { @Override public void run() { - // TODO: Record the chunk start time in chunkStatus. + double downloaded = 0.0; - - // TODO: Print a message that this chunk has started downloading. - + long startTime = System.currentTimeMillis(); + chunkStatus.setStartTimeMs(startTime); + System.out.println("Chunk: " + chunkStatus.getChunkId() + " has 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. + + long randomSleep = random.nextLong(config.getMinStepDelayMs(), config.getMaxStepDelayMs()); + + try { + Thread.sleep(randomSleep); + } + catch (InterruptedException e) { + System.out.println(e.getMessage()); + } + + double down = random.nextDouble(); + downloaded = Math.min(downloaded + down, chunkStatus.getChunkSizeMB()); + chunkStatus.setDownloadedMB(chunkStatus.getDownloadedMB() + 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.setCompleted(true); + Long endTime = System.currentTimeMillis(); + chunkStatus.setEndTimeMs(endTime); + System.out.println("Chunk: " + chunkStatus.getChunkId() + " has completed downloading."); } }