From 015734784fa7e86ac71057ec95373ee3ee185881 Mon Sep 17 00:00:00 2001 From: mohammadreza Date: Mon, 8 Jun 2026 00:36:38 +0330 Subject: [PATCH] implement DownloadWorker.java --- src/main/java/DownloadWorker.java | 60 ++++++++++++++++++++++++------- 1 file changed, 47 insertions(+), 13 deletions(-) diff --git a/src/main/java/DownloadWorker.java b/src/main/java/DownloadWorker.java index 546de2d..f596a9e 100644 --- a/src/main/java/DownloadWorker.java +++ b/src/main/java/DownloadWorker.java @@ -1,4 +1,5 @@ import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; /** * Simulates downloading a single chunk of a file. @@ -11,33 +12,66 @@ 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. + long start = System.currentTimeMillis(); + chunkStatus.setStartTimeMs(start); + 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()) { - // 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 randomSleepDelay = ThreadLocalRandom.current().nextInt( + config.getMinStepDelayMs(), + config.getMaxStepDelayMs() + 1 + ); + + 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. - // TODO: Record the chunk end time in chunkStatus. - // TODO: Print a message that this chunk has finished downloading. + chunkStatus.setCompleted(true); + + long end = System.currentTimeMillis(); + chunkStatus.setEndTimeMs(end); + + System.out.println( + "Chunk (id: " + chunkStatus.getChunkId() + ") has finished downloading. Took: " + + chunkStatus.getDownloadDurationMs() + " ms" + ); } }