Implement download worker
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
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;
|
||||
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.
|
||||
chunkStatus.setStartTimeMs(System.currentTimeMilliS()) ;
|
||||
double downloaded = 0.0;
|
||||
|
||||
// TODO: Print a message that this chunk has started downloading.
|
||||
System.out.println(Thread.currentThread().getName() + " started downloading Chunk #" + chunkStatus.getChunkId());
|
||||
|
||||
while (downloaded < chunkStatus.getChunkSizeMB()) {
|
||||
// TODO: Generate a random sleep delay between min and max delay.
|
||||
int minDelay = config.getMinStepDelayMs() ;
|
||||
int maxDelay = config.getMaxStepDalayMs() ;
|
||||
int delay = minDelay + random.nextInt(maxDelay-minDelay +1) ;
|
||||
|
||||
// TODO: Sleep for that delay.
|
||||
Thread.sleep(delay) ;
|
||||
// TODO: Generate a random download amount for this step.
|
||||
double minStep = config.getMinStepDownloadMB() ;
|
||||
double maxStep = config.getMaxStepDownloadMB() ;
|
||||
double stepDownload = minStep + ((maxStep-minStep)*random.nextDouble()) ;
|
||||
|
||||
|
||||
// TODO: Increase downloaded, but do not go beyond chunk size.
|
||||
downloaded += stepDownload ;
|
||||
if (downloaded > chunkStatus.getChunkSizeMB())
|
||||
{
|
||||
downloaded = chunkStatus.getChunkSizeMB() ;
|
||||
}
|
||||
|
||||
// TODO: Save the updated downloaded value into chunkStatus.
|
||||
chunkStatus.setDownloadedMB(downloaded) ;
|
||||
// TODO: Optionally print step-by-step progress.
|
||||
}
|
||||
|
||||
|
||||
// TODO: Mark the chunk as completed.
|
||||
chunkStatus.setCompleted(true );
|
||||
// TODO: Record the chunk end time in chunkStatus.
|
||||
chunkStatus.setEndTimeMs(System.currentTimeMillis()) ;
|
||||
// TODO: Print a message that this chunk has finished downloading.
|
||||
System.out.println(Thread.currentThread().getName() + " finished downloading Chunk #" + chunkStatus.getChunkId());
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user