Develop #1

Open
Sarazpr wants to merge 2 commits from develop into main
4 changed files with 81 additions and 3 deletions
+40
View File
@@ -0,0 +1,40 @@
## start() vs run()
**Q1**
**the output:**
Calling run()
Running in: main
Calling start()
Running in: Thread-2
**answer to why:** run() is executed by main thread although start() is executed by thread object that been created.
**Q2**
the difference between these two, is that when a thread (which has been created as an object) calls run(), couldn't execute it. So the method will be executed by the thread that created t1.
But by calling start(), you wouldn't see this behavior and method will be executed by thread that been created as t2.
## Deamon Threads
**Q1**
**the output:**
Main thread ends.
Daemon thread running...
**answer to why:** Main thread executes faster than deamon thread and exits the program so it doesn't let deamon thread execute properly.
**Q2**
the thread will execute properly and we'll see "Daemon thread running..." prints for 20 times after printing "Main thread ends.".
**Q3**
for example one of use cases is Logging and Auditing Services. Daemon threads can be used to log background activities continuously.
## A shorter way to create threads
**Q1**
**the output:** Thread is running using a ...!
**Q2**
Java Lambda
**Q3**
it is the easiest way to create a thread. All three ways do the same execution. But with different usages.
+18
View File
@@ -1,5 +1,7 @@
import java.util.Random; import java.util.Random;
import static java.lang.Thread.sleep;
/** /**
* Simulates downloading a single chunk of a file. * Simulates downloading a single chunk of a file.
* *
@@ -22,22 +24,38 @@ public class DownloadWorker implements Runnable {
@Override @Override
public void run() { public void run() {
// TODO: Record the chunk start time in chunkStatus. // TODO: Record the chunk start time in chunkStatus.
chunkStatus.setStartTimeMs(System.currentTimeMillis());
double downloaded = 0.0; double downloaded = 0.0;
// TODO: Print a message that this chunk has started downloading. // TODO: Print a message that this chunk has started downloading.
System.out.println(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: Generate a random sleep delay between min and max delay.
int delayTime = random.nextInt(config.getMinStepDelayMs(), config.getMaxStepDelayMs());
// TODO: Sleep for that delay. // TODO: Sleep for that delay.
try {
Thread.sleep(delayTime);
} catch (InterruptedException e) {
throw new RuntimeException(e); // not sure about this one!
}
// TODO: Generate a random download amount for this step. // TODO: Generate a random download amount for this step.
double currentDownloaded = random.nextDouble(config.getMinStepDownloadMB(), config.getMaxStepDownloadMB());
// TODO: Increase downloaded, but do not go beyond chunk size. // TODO: Increase downloaded, but do not go beyond chunk size.
while (downloaded <= 120) {
downloaded += currentDownloaded;
}
// TODO: Save the updated downloaded value into chunkStatus. // TODO: Save the updated downloaded value into chunkStatus.
chunkStatus.setDownloadedMB(downloaded);
// TODO: Optionally print step-by-step progress. // TODO: Optionally print step-by-step progress.
} }
// TODO: Mark the chunk as completed. // TODO: Mark the chunk as completed.
chunkStatus.setCompleted(true);
// TODO: Record the chunk end time in chunkStatus. // TODO: Record the chunk end time in chunkStatus.
chunkStatus.setEndTimeMs(System.currentTimeMillis());
// TODO: Print a message that this chunk has finished downloading. // TODO: Print a message that this chunk has finished downloading.
System.out.println(chunkStatus.getChunkId() + " has finished downloading.");
} }
} }
+18 -3
View File
@@ -37,7 +37,9 @@ public class Main {
// TODO: // TODO:
// Students may print helpful debug information here, // Students may print helpful debug information here,
// for example which chunk is assigned to which worker thread. // for example which chunk is assigned to which worker thread.
System.out.println(chunk.getChunkId() + " is assigned to " + workerThread.getName());
} }
System.out.println();
// 4. Create and start monitor thread // 4. Create and start monitor thread
ProgressMonitor monitor = new ProgressMonitor(config, chunks); ProgressMonitor monitor = new ProgressMonitor(config, chunks);
@@ -49,11 +51,15 @@ public class Main {
// //
// Example idea: // Example idea:
// monitorThread.start(); // monitorThread.start();
monitorThread.start();
// 5. Start worker threads // 5. Start worker threads
// TODO: // TODO:
// Start each worker thread in workerThreads. // Start each worker thread in workerThreads.
// Use a loop and call start() on each thread. // Use a loop and call start() on each thread.
for (Thread wT: workerThreads){
wT.start();
}
// 6. Wait for workers to finish // 6. Wait for workers to finish
// TODO: // TODO:
@@ -61,9 +67,13 @@ public class Main {
// This should be done inside a try-catch block for InterruptedException. // This should be done inside a try-catch block for InterruptedException.
// //
// Hint: // Hint:
// for (Thread thread : workerThreads) { for (Thread thread : workerThreads) {
// thread.join(); try {
// } thread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
// TODO: // TODO:
// After all workers finish, the monitor thread may also need to stop. // After all workers finish, the monitor thread may also need to stop.
@@ -72,6 +82,11 @@ public class Main {
// - add a stopping mechanism in ProgressMonitor later. // - add a stopping mechanism in ProgressMonitor later.
// //
// If your monitor finishes automatically, you may join it here. // If your monitor finishes automatically, you may join it here.
try {
monitorThread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// NOTE: // NOTE:
// this final report may show 0 progress because no worker has actually run yet. // this final report may show 0 progress because no worker has actually run yet.
+5
View File
@@ -57,6 +57,11 @@ public class ProgressMonitor implements Runnable {
// TODO: // TODO:
// If all chunks are completed, print a final message and exit the loop // If all chunks are completed, print a final message and exit the loop
if (completedChunks == chunks.size())
{
System.out.println("all chunks are completed!");
break;
}
try { try {
Thread.sleep(monitorDelayMs); Thread.sleep(monitorDelayMs);