implement DownloadWorker class
This commit is contained in:
@@ -1,12 +1,5 @@
|
|||||||
import java.util.Random;
|
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 {
|
public class DownloadWorker implements Runnable {
|
||||||
|
|
||||||
private final ChunkStatus chunkStatus;
|
private final ChunkStatus chunkStatus;
|
||||||
@@ -21,23 +14,31 @@ public class DownloadWorker implements Runnable {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// TODO: Record the chunk start time in chunkStatus.
|
|
||||||
double downloaded = 0.0;
|
double downloaded = 0.0;
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
// TODO: Print a message that this chunk has started downloading.
|
chunkStatus.setStartTimeMs(startTime);
|
||||||
|
System.out.println("Chunk: " + 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.
|
long randomSleep = random.nextLong(config.getMinStepDelayMs(), config.getMaxStepDelayMs());
|
||||||
// TODO: Generate a random download amount for this step.
|
|
||||||
// TODO: Increase downloaded, but do not go beyond chunk size.
|
try {
|
||||||
// TODO: Save the updated downloaded value into chunkStatus.
|
Thread.sleep(randomSleep);
|
||||||
// TODO: Optionally print step-by-step progress.
|
}
|
||||||
|
catch (InterruptedException e) {
|
||||||
|
System.out.println(e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Mark the chunk as completed.
|
double down = random.nextDouble();
|
||||||
// TODO: Record the chunk end time in chunkStatus.
|
downloaded = Math.min(downloaded + down, chunkStatus.getChunkSizeMB());
|
||||||
// TODO: Print a message that this chunk has finished downloading.
|
chunkStatus.setDownloadedMB(chunkStatus.getDownloadedMB() + downloaded);
|
||||||
|
}
|
||||||
|
|
||||||
|
chunkStatus.setCompleted(true);
|
||||||
|
Long endTime = System.currentTimeMillis();
|
||||||
|
chunkStatus.setEndTimeMs(endTime);
|
||||||
|
System.out.println("Chunk: " + chunkStatus.getChunkId() + " has completed downloading.");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user