Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5eb6343ba6 |
@@ -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.lang.Thread;
|
||||
|
||||
/**
|
||||
* Simulates downloading a single chunk of a file.
|
||||
@@ -21,23 +23,33 @@ public class DownloadWorker implements Runnable {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// TODO: Record the chunk start time in chunkStatus.
|
||||
// Records current system time
|
||||
chunkStatus.setStartTimeMs(System.currentTimeMillis());
|
||||
|
||||
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()) {
|
||||
// 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.
|
||||
// Sleeps the thread to mimic a part of the chunk being downloaded in the random time.
|
||||
try{
|
||||
Thread.sleep(random.nextInt(5000));
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
// 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.
|
||||
// TODO: Record the chunk end time in chunkStatus.
|
||||
// TODO: Print a message that this chunk has finished downloading.
|
||||
// Sets the chunk status, records the end time
|
||||
chunkStatus.setCompleted(true);
|
||||
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);
|
||||
|
||||
// TODO:
|
||||
// Students may print helpful debug information here,
|
||||
// for example which chunk is assigned to which worker thread.
|
||||
System.out.println("Chunk with id: " + chunk.getChunkId() + " is assigned to Thread: " + workerThread.getName());
|
||||
}
|
||||
|
||||
// 4. Create and start monitor thread
|
||||
ProgressMonitor monitor = new ProgressMonitor(config, chunks);
|
||||
Thread monitorThread = new Thread(monitor, "Progress-Monitor");
|
||||
|
||||
// TODO:
|
||||
// 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 & monitor thread
|
||||
|
||||
// 5. Start worker threads
|
||||
// TODO:
|
||||
// Start each worker thread in workerThreads.
|
||||
// Use a loop and call start() on each thread.
|
||||
monitorThread.start();
|
||||
for (Thread workerThread : workerThreads){
|
||||
workerThread.start();
|
||||
}
|
||||
|
||||
// 6. Wait for workers to finish
|
||||
// TODO:
|
||||
// Wait for all worker threads to complete by calling join().
|
||||
// This should be done inside a try-catch block for InterruptedException.
|
||||
//
|
||||
// Hint:
|
||||
// for (Thread thread : workerThreads) {
|
||||
// thread.join();
|
||||
// }
|
||||
// 6. Wait for the workers to finish
|
||||
for (Thread workerThread : workerThreads){
|
||||
try {
|
||||
workerThread.join();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO:
|
||||
// After all workers finish, the monitor thread may also need to stop.
|
||||
// Depending on how ProgressMonitor is implemented, students may:
|
||||
// - wait for it to finish on its own, or
|
||||
// - 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,
|
||||
try {
|
||||
monitorThread.join();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
// 7. Print final report
|
||||
System.out.println();
|
||||
|
||||
@@ -16,17 +16,6 @@ public class ProgressMonitor implements Runnable {
|
||||
|
||||
@Override
|
||||
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) {
|
||||
double totalDownloadedMB = 0.0;
|
||||
int completedChunks = 0;
|
||||
@@ -54,15 +43,18 @@ public class ProgressMonitor implements Runnable {
|
||||
chunks.size()
|
||||
);
|
||||
|
||||
|
||||
// TODO:
|
||||
// If all chunks are completed, print a final message and exit the loop
|
||||
|
||||
try {
|
||||
Thread.sleep(monitorDelayMs);
|
||||
} catch (InterruptedException e) {
|
||||
System.out.println("Progress monitor interrupted.");
|
||||
return;
|
||||
if (completedChunks == chunks.size()){
|
||||
System.out.println("All workers finished their job, downloaded the file successfully. \nHere's the report: ");
|
||||
for (ChunkStatus chunk : chunks){
|
||||
System.out.println(chunk.toString());
|
||||
}
|
||||
break;
|
||||
}else {
|
||||
try {
|
||||
Thread.sleep(monitorDelayMs);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user