Merge pull request 'tamrin 8' (#1) from develop into main
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
@@ -0,0 +1,124 @@
|
|||||||
|
## 1 . `start()` vs `run()` :
|
||||||
|
|
||||||
|
```
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
### Questions and Answers:
|
||||||
|
* **What output do you get from the program? Why?**
|
||||||
|
* ```
|
||||||
|
//output:
|
||||||
|
Calling run()
|
||||||
|
Running in : main
|
||||||
|
Calling start()
|
||||||
|
Running in : Thread-2
|
||||||
|
```
|
||||||
|
* *When `t1.run()` is called directly, it executes the `run()` method in the current thread (the main thread), just like a normal method call. No new thread is created. Therefore, `Thread.currentThread().getName()` returns `"main"`.*
|
||||||
|
<br>
|
||||||
|
* *When `t2.start()` is called, it creates a new thread named `"Thread-2"` and the JVM automatically invokes the `run()` method inside that new thread. Hence, `Thread.currentThread().getName()` returns `"Thread-2"`.*
|
||||||
|
<br>
|
||||||
|
* **What’s the difference in behavior between calling `start()` and `run()`?**
|
||||||
|
<br>
|
||||||
|
* *Calling `run()` directly just executes the code inside `run()` in the caller's thread – it's not multithreading.*
|
||||||
|
<br>
|
||||||
|
* *Calling `start()` schedules the thread to run, and the `run()` method will be executed in a separate thread concurrently.*
|
||||||
|
|
||||||
|
***
|
||||||
|
|
||||||
|
## 2. Daemon Threads :
|
||||||
|
```
|
||||||
|
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.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
### Questions and Answers:
|
||||||
|
|
||||||
|
* **What output do you get from the program? Why?**
|
||||||
|
* ```
|
||||||
|
//output:
|
||||||
|
Main thread ends.
|
||||||
|
Daemon thread running...
|
||||||
|
Daemon thread running...
|
||||||
|
...
|
||||||
|
//(less than 20 times)
|
||||||
|
```
|
||||||
|
* *The main thread prints `"Main thread ends."` and then terminates.*
|
||||||
|
<br>
|
||||||
|
* *The other thread is a `daemon thread`. Daemon threads are background threads that do not prevent the JVM from exiting.*
|
||||||
|
<br>
|
||||||
|
* *When the last non-daemon thread (in this case, only the main thread) finishes, the JVM terminates immediately without waiting for the daemon thread to complete its loop.*
|
||||||
|
<br>
|
||||||
|
* *Therefore, the daemon thread only gets to print a few lines before the program shuts down. It never reaches 20 iterations.*
|
||||||
|
<br>
|
||||||
|
* **What happens if you remove thread.setDaemon(true)?**
|
||||||
|
<br>
|
||||||
|
* *The thread prints 20 times and then the program ends, because the thread is no longer a daemon (it becomes a regular user thread).*
|
||||||
|
* **What are some real-life use cases of daemon threads?**
|
||||||
|
<br>
|
||||||
|
1. *Background music in a game – While you play, music plays in the background. When you close the game, the music stops immediately. No need to finish the song.*
|
||||||
|
<br>
|
||||||
|
2. *Auto-save in a text editor – Every few minutes, the program saves your file automatically. If you close the program, it doesn't matter if the auto-save finishes or not. Just stop.*
|
||||||
|
<br>
|
||||||
|
|
||||||
|
***
|
||||||
|
|
||||||
|
## 3. A shorter way to create threads :
|
||||||
|
```
|
||||||
|
public class ThreadDemo {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Thread thread = new Thread(() -> {
|
||||||
|
System.out.println("Thread is running using a ...!");
|
||||||
|
});
|
||||||
|
|
||||||
|
thread.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
### Questions and Answers:
|
||||||
|
|
||||||
|
* **What output do you get from the program?**
|
||||||
|
* ```
|
||||||
|
//output:
|
||||||
|
Thread is running using a ...!
|
||||||
|
```
|
||||||
|
* **What is the `() -> { ... }` syntax called?**
|
||||||
|
<br>
|
||||||
|
* *It is called a Lambda Expression*
|
||||||
|
<br>
|
||||||
|
* **How is this code different from creating a class that extends `Thread` or implements `Runnable`?**
|
||||||
|
<br>
|
||||||
|
* *Shorter and cleaner code.*
|
||||||
|
* *No need for a separate class or explicit `run()` override.*
|
||||||
|
* *Lambda directly provides the `run()` body.*
|
||||||
@@ -21,23 +21,48 @@ public class DownloadWorker implements Runnable {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// 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.
|
System.out.println(Thread.currentThread().getName() + " started downloading chunk " +
|
||||||
|
chunkStatus.getChunkId() + " (" + chunkStatus.getChunkSizeMB() + " MB)");
|
||||||
|
|
||||||
while (downloaded < chunkStatus.getChunkSizeMB()) {
|
while (downloaded < chunkStatus.getChunkSizeMB()) {
|
||||||
// TODO: Generate a random sleep delay between min and max delay.
|
int delayMs = config.getMinStepDelayMs() +
|
||||||
// TODO: Sleep for that delay.
|
random.nextInt(config.getMaxStepDelayMs() - config.getMinStepDelayMs() + 1);
|
||||||
// TODO: Generate a random download amount for this step.
|
try {
|
||||||
// TODO: Increase downloaded, but do not go beyond chunk size.
|
Thread.sleep(delayMs);
|
||||||
// TODO: Save the updated downloaded value into chunkStatus.
|
} catch (InterruptedException e) {
|
||||||
// TODO: Optionally print step-by-step progress.
|
System.out.println(Thread.currentThread().getName() + " interrupted");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate random download amount for this step
|
||||||
|
double step = config.getMinStepDownloadMB() +
|
||||||
|
random.nextDouble() * (config.getMaxStepDownloadMB() - config.getMinStepDownloadMB());
|
||||||
|
downloaded += step;
|
||||||
|
if (downloaded > chunkStatus.getChunkSizeMB()) {
|
||||||
|
downloaded = chunkStatus.getChunkSizeMB();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update shared status
|
||||||
|
chunkStatus.setDownloadedMB(downloaded);
|
||||||
|
|
||||||
|
// Optional step progress print
|
||||||
|
System.out.printf("%s: chunk %d -> %.2f / %.2f MB (%.1f%%)%n",
|
||||||
|
Thread.currentThread().getName(),
|
||||||
|
chunkStatus.getChunkId(),
|
||||||
|
downloaded,
|
||||||
|
chunkStatus.getChunkSizeMB(),
|
||||||
|
(downloaded / chunkStatus.getChunkSizeMB()) * 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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 chunk " +
|
||||||
|
chunkStatus.getChunkId() + " in " +
|
||||||
|
(chunkStatus.getEndTimeMs() - chunkStatus.getStartTimeMs()) + " ms");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-32
@@ -34,48 +34,35 @@ public class Main {
|
|||||||
|
|
||||||
workerThreads.add(workerThread);
|
workerThreads.add(workerThread);
|
||||||
|
|
||||||
// TODO:
|
System.out.println("Created " + workerThread.getName() +
|
||||||
// Students may print helpful debug information here,
|
" for chunk " + chunk.getChunkId() +
|
||||||
// for example which chunk is assigned to which worker thread.
|
" (size: " + chunk.getChunkSizeMB() + " MB)");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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");
|
||||||
|
monitorThread.start();
|
||||||
// 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
|
// 5. Start worker threads
|
||||||
// TODO:
|
for (Thread t : workerThreads) {
|
||||||
// Start each worker thread in workerThreads.
|
t.start();
|
||||||
// Use a loop and call start() on each thread.
|
}
|
||||||
|
|
||||||
// 6. Wait for workers to finish
|
// 6. Wait for workers to finish
|
||||||
// TODO:
|
for (Thread t : workerThreads) {
|
||||||
// Wait for all worker threads to complete by calling join().
|
try {
|
||||||
// This should be done inside a try-catch block for InterruptedException.
|
t.join();
|
||||||
//
|
} catch (InterruptedException e) {
|
||||||
// Hint:
|
System.out.println("Main interrupted while waiting for workers.");
|
||||||
// for (Thread thread : workerThreads) {
|
}
|
||||||
// thread.join();
|
}
|
||||||
// }
|
|
||||||
|
|
||||||
// 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.
|
||||||
// Depending on how ProgressMonitor is implemented, students may:
|
try {
|
||||||
// - wait for it to finish on its own, or
|
monitorThread.join();
|
||||||
// - add a stopping mechanism in ProgressMonitor later.
|
} catch (InterruptedException e) {
|
||||||
//
|
System.out.println("Main interrupted while waiting for monitor.");
|
||||||
// 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,16 +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;
|
||||||
@@ -55,8 +45,10 @@ public class ProgressMonitor implements Runnable {
|
|||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
// TODO:
|
if (completedChunks == chunks.size()) {
|
||||||
// If all chunks are completed, print a final message and exit the loop
|
System.out.println("All chunks completed. Monitor thread stopping.");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Thread.sleep(monitorDelayMs);
|
Thread.sleep(monitorDelayMs);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
fileName=movie.mkv
|
fileName=movie.mkv
|
||||||
totalSizeMB=120
|
totalSizeMB=120
|
||||||
chunkCount=6
|
chunkCount=6
|
||||||
minStepDelayMs=80
|
minStepDelayMs=80
|
||||||
maxStepDelayMs=200
|
maxStepDelayMs=200
|
||||||
minStepDownloadMB=2
|
minStepDownloadMB=2
|
||||||
maxStepDownloadMB=6
|
maxStepDownloadMB=6
|
||||||
Reference in New Issue
Block a user