complete code
This commit is contained in:
@@ -1,12 +1,5 @@
|
||||
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;
|
||||
@@ -21,23 +14,43 @@ public class DownloadWorker implements Runnable {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// TODO: Record the chunk start time in chunkStatus.
|
||||
double downloaded = 0.0;
|
||||
chunkStatus.setStartTimeMs(System.currentTimeMillis());
|
||||
|
||||
// TODO: Print a message that this chunk has started downloading.
|
||||
double downloaded = 0;
|
||||
|
||||
System.out.println("Chunk " + chunkStatus.getChunkId() + " started.");
|
||||
|
||||
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 = random.nextInt(
|
||||
config.getMaxStepDelayMs() - config.getMinStepDelayMs() + 1
|
||||
) + config.getMinStepDelayMs();
|
||||
|
||||
try {
|
||||
Thread.sleep(delay);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
double amount = random.nextDouble() *
|
||||
(config.getMaxStepDownloadMB() - config.getMinStepDownloadMB())
|
||||
+ config.getMinStepDownloadMB();
|
||||
|
||||
downloaded = downloaded + amount;
|
||||
|
||||
if (downloaded > chunkStatus.getChunkSizeMB()) {
|
||||
downloaded = chunkStatus.getChunkSizeMB();
|
||||
}
|
||||
|
||||
chunkStatus.setDownloadedMB(downloaded);
|
||||
|
||||
System.out.println("Chunk " + chunkStatus.getChunkId()
|
||||
+ ": " + 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);
|
||||
chunkStatus.setEndTimeMs(System.currentTimeMillis());
|
||||
|
||||
}
|
||||
System.out.println("Chunk " + chunkStatus.getChunkId() + " finished.");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user