Added REPORT.md for the theoretical questions
Finished ProgressMonitor, DownloadWorker and Main classes.
This commit is contained in:
@@ -0,0 +1,86 @@
|
|||||||
|
## Q1
|
||||||
|
```java
|
||||||
|
public class StartVsRun {
|
||||||
|
static class MyRunnable implements Runnable {
|
||||||
|
public void run() {
|
||||||
|
System.out.println("Running in: " + Thread.currentThread().getName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public static void main(String[] args) throws InterruptedException {
|
||||||
|
Thread t1 = new Thread(new MyRunnable(), "Thread-1");
|
||||||
|
System.out.println("Calling run()");
|
||||||
|
t1.run();
|
||||||
|
Thread.sleep(100);
|
||||||
|
|
||||||
|
Thread t2 = new Thread(new MyRunnable(), "Thread-2");
|
||||||
|
System.out.println("Calling start()");
|
||||||
|
t2.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
### Answer
|
||||||
|
#### Output
|
||||||
|
the program first outputs `Calling run()`
|
||||||
|
then it runs the `t1` by calling the `run` method in the `t1` thread
|
||||||
|
t1's run method outputs `Running in: Thread-1`
|
||||||
|
|
||||||
|
the program waits 100ms (`Thread.sleep(100)`) after that a new thread is created called `t2`
|
||||||
|
the program outputs `Calling start()` and then `Running in: Thread-2`
|
||||||
|
|
||||||
|
#### Difference between `run()` and `start()`
|
||||||
|
when we call `t1.run()` the program stops at this line, no new thread would be created and run method runs on the main thread
|
||||||
|
but when we call `t2.start()` a new thread would get created and main thread runs alongside the new thread.
|
||||||
|
|
||||||
|
## Q2
|
||||||
|
```java
|
||||||
|
public class DaemonExample {
|
||||||
|
static class DaemonRunnable implements Runnable {
|
||||||
|
public void run() {
|
||||||
|
for(int i = 0; i < 20; i++) {
|
||||||
|
System.out.println("Daemon thread running...");
|
||||||
|
try {
|
||||||
|
Thread.sleep(500);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
//[Handling Exception...]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Thread thread = new Thread(new DaemonRunnable());
|
||||||
|
thread.setDaemon(true);
|
||||||
|
thread.start();
|
||||||
|
System.out.println("Main thread ends.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
### Answer
|
||||||
|
#### Output
|
||||||
|
The program creates a thread from DaemonRunnable class, after that it sets to a be a daemon output first message: `Daemon thread running...` and just as it's in sleep (`Thread.sleep(500)`) the main thread finishes its job
|
||||||
|
and outputs: `Main thread ends.`. this would end the daemon thread we started.
|
||||||
|
#### What if we removed `thread.setDaemon(true)`
|
||||||
|
if we removed this line `thread` would've been a normal thread, meaning when we reach the end of the main thread `thread` would still continue doing its work (which is printing `Daemon thread running...`)
|
||||||
|
The Main thread would've waited for `thread` to finish its job before ending the program.
|
||||||
|
#### Real life use cases
|
||||||
|
`sshd` is a daemon that listens for any SSH connections to the computer
|
||||||
|
another example would be `systemd` which is a daemon on most of the linux distros that manages services
|
||||||
|
|
||||||
|
## Q3
|
||||||
|
```java
|
||||||
|
public class ThreadDemo {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Thread thread = new Thread(() -> {
|
||||||
|
System.out.println("Thread is running using a ...!");
|
||||||
|
});
|
||||||
|
|
||||||
|
thread.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
### Answer
|
||||||
|
#### Output
|
||||||
|
the program simply just outputs `Thread is running using a ...!`
|
||||||
|
#### What is the `() -> {...}` syntax called
|
||||||
|
`() -> {...}` is a lambda expression with no parameters: `()`
|
||||||
|
#### Difference between this and a normal class
|
||||||
|
using this lambda expression we don't need to create another class
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
|
import java.time.LocalTime;
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
|
import java.lang.Thread;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simulates downloading a single chunk of a file.
|
* Simulates downloading a single chunk of a file.
|
||||||
@@ -21,23 +23,33 @@ public class DownloadWorker implements Runnable {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// TODO: Record the chunk start time in chunkStatus.
|
// Records current system time
|
||||||
|
chunkStatus.setStartTimeMs(System.currentTimeMillis());
|
||||||
|
|
||||||
double downloaded = 0.0;
|
double downloaded = 0.0;
|
||||||
|
|
||||||
// TODO: Print a message that this chunk has started downloading.
|
System.out.println("A new chunk downloader with id: " + chunkStatus.getChunkId() + " started downloading...");
|
||||||
|
|
||||||
while (downloaded < chunkStatus.getChunkSizeMB()) {
|
while (downloaded < chunkStatus.getChunkSizeMB()) {
|
||||||
// TODO: Generate a random sleep delay between min and max delay.
|
// Sleeps the thread to mimic a part of the chunk being downloaded in the random time.
|
||||||
// TODO: Sleep for that delay.
|
try{
|
||||||
// TODO: Generate a random download amount for this step.
|
Thread.sleep(random.nextInt(5000));
|
||||||
// TODO: Increase downloaded, but do not go beyond chunk size.
|
} catch (InterruptedException e) {
|
||||||
// TODO: Save the updated downloaded value into chunkStatus.
|
throw new RuntimeException(e);
|
||||||
// TODO: Optionally print step-by-step progress.
|
}
|
||||||
|
|
||||||
|
// Gets a random number as the downloaded size in the random timespan
|
||||||
|
double downloadedSizeMB = random.nextDouble(chunkStatus.getChunkSizeMB());
|
||||||
|
downloaded += downloadedSizeMB;
|
||||||
|
chunkStatus.setDownloadedMB(downloaded);
|
||||||
|
|
||||||
|
System.out.println("Downloaded: " + downloadedSizeMB + "MBs.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Mark the chunk as completed.
|
// Sets the chunk status, records the end time
|
||||||
// TODO: Record the chunk end time in chunkStatus.
|
chunkStatus.setCompleted(true);
|
||||||
// TODO: Print a message that this chunk has finished downloading.
|
chunkStatus.setEndTimeMs(System.currentTimeMillis());
|
||||||
|
System.out.println("Chunk downloader with id: " + chunkStatus.getChunkId() + " finished its work.");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-33
@@ -34,48 +34,34 @@ public class Main {
|
|||||||
|
|
||||||
workerThreads.add(workerThread);
|
workerThreads.add(workerThread);
|
||||||
|
|
||||||
// TODO:
|
System.out.println("Chunk with id: " + chunk.getChunkId() + " is assigned to Thread: " + workerThread.getName());
|
||||||
// Students may print helpful debug information here,
|
|
||||||
// for example which chunk is assigned to which worker thread.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Create and start monitor thread
|
// 4. Create and start monitor thread
|
||||||
ProgressMonitor monitor = new ProgressMonitor(config, chunks);
|
ProgressMonitor monitor = new ProgressMonitor(config, chunks);
|
||||||
Thread monitorThread = new Thread(monitor, "Progress-Monitor");
|
Thread monitorThread = new Thread(monitor, "Progress-Monitor");
|
||||||
|
|
||||||
// TODO:
|
// 5. Start worker threads & monitor thread
|
||||||
// Start the monitor thread before starting the workers
|
|
||||||
// so that progress can be displayed while downloading happens.
|
|
||||||
//
|
|
||||||
// Example idea:
|
|
||||||
// monitorThread.start();
|
|
||||||
|
|
||||||
// 5. Start worker threads
|
monitorThread.start();
|
||||||
// TODO:
|
for (Thread workerThread : workerThreads){
|
||||||
// Start each worker thread in workerThreads.
|
workerThread.start();
|
||||||
// Use a loop and call start() on each thread.
|
}
|
||||||
|
|
||||||
// 6. Wait for workers to finish
|
// 6. Wait for the workers to finish
|
||||||
// TODO:
|
for (Thread workerThread : workerThreads){
|
||||||
// Wait for all worker threads to complete by calling join().
|
try {
|
||||||
// This should be done inside a try-catch block for InterruptedException.
|
workerThread.join();
|
||||||
//
|
} catch (InterruptedException e) {
|
||||||
// Hint:
|
throw new RuntimeException(e);
|
||||||
// for (Thread thread : workerThreads) {
|
}
|
||||||
// thread.join();
|
}
|
||||||
// }
|
|
||||||
|
|
||||||
// TODO:
|
try {
|
||||||
// After all workers finish, the monitor thread may also need to stop.
|
monitorThread.join();
|
||||||
// Depending on how ProgressMonitor is implemented, students may:
|
} catch (InterruptedException e) {
|
||||||
// - wait for it to finish on its own, or
|
throw new RuntimeException(e);
|
||||||
// - add a stopping mechanism in ProgressMonitor later.
|
}
|
||||||
//
|
|
||||||
// If your monitor finishes automatically, you may join it here.
|
|
||||||
|
|
||||||
// NOTE:
|
|
||||||
// this final report may show 0 progress because no worker has actually run yet.
|
|
||||||
// Until students complete the thread start/join TODOs above,
|
|
||||||
|
|
||||||
// 7. Print final report
|
// 7. Print final report
|
||||||
System.out.println();
|
System.out.println();
|
||||||
|
|||||||
@@ -16,17 +16,6 @@ public class ProgressMonitor implements Runnable {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// TODO:
|
|
||||||
// Repeatedly check chunk progress until all chunks are completed.
|
|
||||||
// In each loop:
|
|
||||||
// 1. Read the downloaded size from every chunk
|
|
||||||
// 2. Add all downloaded amounts to totalDownloadedMB
|
|
||||||
// 3. Count completed chunks
|
|
||||||
// 4. Print a progress message
|
|
||||||
// 5. If completedChunks == chunks.size(), print a final monitor message and stop
|
|
||||||
// 6. Otherwise sleep for monitorDelayMs and continue
|
|
||||||
|
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
double totalDownloadedMB = 0.0;
|
double totalDownloadedMB = 0.0;
|
||||||
int completedChunks = 0;
|
int completedChunks = 0;
|
||||||
@@ -54,15 +43,18 @@ public class ProgressMonitor implements Runnable {
|
|||||||
chunks.size()
|
chunks.size()
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (completedChunks == chunks.size()){
|
||||||
// TODO:
|
System.out.println("All workers finished their job, downloaded the file successfully. \nHere's the report: ");
|
||||||
// If all chunks are completed, print a final message and exit the loop
|
for (ChunkStatus chunk : chunks){
|
||||||
|
System.out.println(chunk.toString());
|
||||||
try {
|
}
|
||||||
Thread.sleep(monitorDelayMs);
|
break;
|
||||||
} catch (InterruptedException e) {
|
}else {
|
||||||
System.out.println("Progress monitor interrupted.");
|
try {
|
||||||
return;
|
Thread.sleep(monitorDelayMs);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user