Develop #1
@@ -0,0 +1,92 @@
|
|||||||
|
|
||||||
|
## Question 1: `start()` vs `run()`
|
||||||
|
|
||||||
|
### What output do you get from the program?
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
The first call (`t1.run()`) prints `Running in: main` because it executes on the **main thread** directly — no new thread is created. The second call (`t2.start()`) properly spawns a new thread, so it prints `Running in: Thread-2`.
|
||||||
|
|
||||||
|
The `Thread.sleep(100)` between the two calls ensures `t2`'s output isn't interleaved with the first, but the ordering of the second line is still technically non-deterministic (it will almost always appear after `"Calling start()"`).
|
||||||
|
|
||||||
|
### What's the difference between `start()` and `run()`?
|
||||||
|
|
||||||
|
| | `run()` | `start()` |
|
||||||
|
|---|---|---|
|
||||||
|
| **Execution** | Runs on the **calling thread** (like a normal method call) | Spawns a **new OS thread** and runs `run()` on it |
|
||||||
|
| **Concurrency** | None — sequential, blocking | Concurrent — the calling thread continues immediately |
|
||||||
|
| **Thread name** | Uses the calling thread's name (`main`) | Uses the new thread's name (`Thread-2`) |
|
||||||
|
| **Thread lifecycle** | Does not transition the thread to `RUNNABLE` state | Properly starts the thread lifecycle |
|
||||||
|
|
||||||
|
Calling `run()` directly is just a regular method call. Only `start()` actually creates a new thread.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Question 2: Daemon Threads
|
||||||
|
|
||||||
|
### What output do you get from the program?
|
||||||
|
|
||||||
|
```
|
||||||
|
Main thread ends.
|
||||||
|
Daemon thread running...
|
||||||
|
Daemon thread running...
|
||||||
|
(possibly a few more lines, then the program exits abruptly)
|
||||||
|
```
|
||||||
|
|
||||||
|
The exact number of "Daemon thread running..." lines is non-deterministic — typically 0 to 2. The JVM shuts down as soon as the **main thread** finishes, which kills all remaining daemon threads immediately, regardless of what they're doing.
|
||||||
|
|
||||||
|
### What happens if you remove `thread.setDaemon(true)`?
|
||||||
|
|
||||||
|
The thread becomes a regular (non-daemon) **user thread**. The JVM will **not exit** until all user threads complete. In this case, the loop runs all 20 iterations (taking ~10 seconds), printing `"Daemon thread running..."` 20 times before the program ends.
|
||||||
|
|
||||||
|
### Real-life use cases of daemon threads
|
||||||
|
|
||||||
|
- **Garbage Collector** – The JVM's own GC runs as a daemon thread; it should never prevent the JVM from shutting down.
|
||||||
|
- **Background logging** – Flushing logs or metrics to a file/server periodically, where losing the last few entries on shutdown is acceptable.
|
||||||
|
- **Heartbeat / keep-alive threads** – Sending periodic pings to a server while the application is alive.
|
||||||
|
- **Cache invalidation** – A background thread that evicts stale entries from an in-memory cache.
|
||||||
|
- **Auto-save** – Periodically saving a draft in an editor; the user closing the app shouldn't be blocked by this.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Question 3: A Shorter Way to Create Threads (Lambda)
|
||||||
|
|
||||||
|
### What output do you get from the program?
|
||||||
|
|
||||||
|
```
|
||||||
|
Thread is running using a ...!
|
||||||
|
```
|
||||||
|
|
||||||
|
(Printed from the newly spawned thread.)
|
||||||
|
|
||||||
|
### What is the `() -> { ... }` syntax called?
|
||||||
|
|
||||||
|
It is called a **lambda expression** (introduced in Java 8). It provides a concise way to implement a **functional interface** — an interface with exactly one abstract method. Since `Runnable` has only one method (`run()`), a lambda can be used anywhere a `Runnable` is expected.
|
||||||
|
|
||||||
|
### How is this different from extending `Thread` or implementing `Runnable`?
|
||||||
|
|
||||||
|
| Approach | Code required | Reusability | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `extends Thread` | Full class definition | Low — must subclass `Thread`, can't extend anything else | Tightly couples logic to thread machinery |
|
||||||
|
| `implements Runnable` | Full class + `new Thread(r)` | Higher — decouples task from thread | Preferred for named/reusable task classes |
|
||||||
|
| **Lambda** | One-liner inline | Low — anonymous, inline only | Best for short, one-off tasks |
|
||||||
|
|
||||||
|
The lambda approach is essentially **anonymous shorthand for `implements Runnable`** — the compiler generates an implementation of `Runnable.run()` under the hood. It is the most concise option but is best suited for simple, short tasks. For complex or reusable tasks, a named class implementing `Runnable` is clearer.
|
||||||
|
|
||||||
|
```java
|
||||||
|
// These three are functionally equivalent:
|
||||||
|
|
||||||
|
// 1. Class extending Thread
|
||||||
|
class MyThread extends Thread {
|
||||||
|
public void run() { System.out.println("Running"); }
|
||||||
|
}
|
||||||
|
new MyThread().start();
|
||||||
|
|
||||||
|
// 2. Anonymous Runnable
|
||||||
|
new Thread(new Runnable() {
|
||||||
|
public void run() { System.out.println("Running"); }
|
||||||
|
}).start();
|
||||||
|
|
||||||
|
// 3. Lambda (shortest)
|
||||||
|
new Thread(() -> System.out.println("Running")).start();
|
||||||
|
```
|
||||||
@@ -1,12 +1,5 @@
|
|||||||
import java.util.Random;
|
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 {
|
public class DownloadWorker implements Runnable {
|
||||||
|
|
||||||
private final ChunkStatus chunkStatus;
|
private final ChunkStatus chunkStatus;
|
||||||
@@ -21,23 +14,32 @@ public class DownloadWorker implements Runnable {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// TODO: Record the chunk start time in chunkStatus.
|
|
||||||
double downloaded = 0.0;
|
double downloaded = 0.0;
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
// TODO: Print a message that this chunk has started downloading.
|
chunkStatus.setStartTimeMs(startTime);
|
||||||
|
System.out.println("Chunk: " + 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: Sleep for that delay.
|
long randomSleep = random.nextLong(config.getMinStepDelayMs(), config.getMaxStepDelayMs());
|
||||||
// TODO: Generate a random download amount for this step.
|
|
||||||
// TODO: Increase downloaded, but do not go beyond chunk size.
|
try {
|
||||||
// TODO: Save the updated downloaded value into chunkStatus.
|
Thread.sleep(randomSleep);
|
||||||
// TODO: Optionally print step-by-step progress.
|
}
|
||||||
|
catch (InterruptedException e) {
|
||||||
|
System.out.println(e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
double down = random.nextDouble();
|
||||||
|
downloaded = Math.min(downloaded + down, chunkStatus.getChunkSizeMB());
|
||||||
|
chunkStatus.setDownloadedMB(chunkStatus.getDownloadedMB() + down);
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Mark the chunk as completed.
|
chunkStatus.setCompleted(true);
|
||||||
// TODO: Record the chunk end time in chunkStatus.
|
Long endTime = System.currentTimeMillis();
|
||||||
// TODO: Print a message that this chunk has finished downloading.
|
chunkStatus.setEndTimeMs(endTime);
|
||||||
|
System.out.println("Chunk: " + chunkStatus.getChunkId() +
|
||||||
|
" has completed downloading (" + chunkStatus.getDownloadDurationMs() +" ms)");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+33
-47
@@ -1,5 +1,6 @@
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
public class Main {
|
public class Main {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
@@ -19,13 +20,13 @@ public class Main {
|
|||||||
System.out.println("Chunk count: " + config.getChunkCount());
|
System.out.println("Chunk count: " + config.getChunkCount());
|
||||||
System.out.println();
|
System.out.println();
|
||||||
|
|
||||||
// 2. Create chunks
|
|
||||||
List<ChunkStatus> chunks = ChunkUtils.createChunks(
|
List<ChunkStatus> chunks = ChunkUtils.createChunks(
|
||||||
config.getTotalSizeMB(),
|
config.getTotalSizeMB(),
|
||||||
config.getChunkCount()
|
config.getChunkCount()
|
||||||
);
|
);
|
||||||
|
|
||||||
// 3. Create worker threads
|
|
||||||
List<Thread> workerThreads = new ArrayList<>();
|
List<Thread> workerThreads = new ArrayList<>();
|
||||||
|
|
||||||
for (ChunkStatus chunk : chunks) {
|
for (ChunkStatus chunk : chunks) {
|
||||||
@@ -34,50 +35,37 @@ public class Main {
|
|||||||
|
|
||||||
workerThreads.add(workerThread);
|
workerThreads.add(workerThread);
|
||||||
|
|
||||||
// TODO:
|
System.out.println("Assigned Worker-" + chunk.getChunkId()
|
||||||
// Students may print helpful debug information here,
|
+ " to chunk #" + chunk.getChunkId()
|
||||||
// for example which chunk is assigned to which worker thread.
|
+ " (" + chunk.getChunkSizeMB() + " MB)");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Create and start monitor thread
|
System.out.println();
|
||||||
|
|
||||||
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:
|
for (Thread workerThread : workerThreads) {
|
||||||
// Start the monitor thread before starting the workers
|
workerThread.start();
|
||||||
// so that progress can be displayed while downloading happens.
|
}
|
||||||
//
|
|
||||||
// Example idea:
|
|
||||||
// monitorThread.start();
|
|
||||||
|
|
||||||
// 5. Start worker threads
|
for (Thread workerThread : workerThreads) {
|
||||||
// TODO:
|
try {
|
||||||
// Start each worker thread in workerThreads.
|
workerThread.join();
|
||||||
// Use a loop and call start() on each thread.
|
} catch (InterruptedException e) {
|
||||||
|
System.out.println("Thread was interrupted: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 6. Wait for workers to finish
|
try {
|
||||||
// TODO:
|
monitorThread.join();
|
||||||
// Wait for all worker threads to complete by calling join().
|
}
|
||||||
// This should be done inside a try-catch block for InterruptedException.
|
catch (InterruptedException e) {
|
||||||
//
|
System.out.println("Thread was interrupted: " + e.getMessage());
|
||||||
// Hint:
|
}
|
||||||
// for (Thread thread : workerThreads) {
|
|
||||||
// thread.join();
|
|
||||||
// }
|
|
||||||
|
|
||||||
// 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,
|
|
||||||
|
|
||||||
// 7. Print final report
|
|
||||||
System.out.println();
|
System.out.println();
|
||||||
System.out.println("=== Final Report ===");
|
System.out.println("=== Final Report ===");
|
||||||
|
|
||||||
@@ -91,17 +79,15 @@ public class Main {
|
|||||||
completedChunks++;
|
completedChunks++;
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println(
|
System.out.printf(" Chunk %d: %.2f/%.0f MB | Duration: %d ms%n",
|
||||||
"Chunk " + chunk.getChunkId()
|
chunk.getChunkId(), chunk.getDownloadedMB(),
|
||||||
+ ": " + chunk.getDownloadedMB()
|
chunk.getChunkSizeMB(), chunk.getDownloadDurationMs());
|
||||||
+ "/" + chunk.getChunkSizeMB()
|
|
||||||
+ " MB"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println();
|
System.out.println();
|
||||||
System.out.println("Completed chunks: " + completedChunks + "/" + chunks.size());
|
System.out.println("Completed chunks : " + completedChunks + "/" + chunks.size());
|
||||||
System.out.println("Downloaded total: " + downloadedMB + "/" + config.getTotalSizeMB() + " MB");
|
System.out.printf("Downloaded total : %.2f/%d MB%n", downloadedMB, config.getTotalSizeMB());
|
||||||
System.out.println("Simulation finished.");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,16 +16,7 @@ public class ProgressMonitor implements Runnable {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// TODO:
|
double previousProgress = 0.0;
|
||||||
// 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;
|
||||||
@@ -44,25 +35,49 @@ public class ProgressMonitor implements Runnable {
|
|||||||
percent = (totalDownloadedMB * 100.0) / totalSizeMB;
|
percent = (totalDownloadedMB * 100.0) / totalSizeMB;
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.printf(
|
|
||||||
"Progress for %s: %.1f/%.1f MB (%.2f%%), completed chunks: %d/%d%n",
|
double deltaMB = totalDownloadedMB - previousProgress;
|
||||||
fileName,
|
double speedMBps = deltaMB / (monitorDelayMs / 1000.0);
|
||||||
totalDownloadedMB,
|
previousProgress = totalDownloadedMB;
|
||||||
(double) totalSizeMB,
|
|
||||||
percent,
|
|
||||||
completedChunks,
|
|
||||||
chunks.size()
|
|
||||||
);
|
|
||||||
|
|
||||||
|
|
||||||
// TODO:
|
double remainingMB = totalSizeMB - totalDownloadedMB;
|
||||||
// If all chunks are completed, print a final message and exit the loop
|
long etaSeconds = (speedMBps > 0) ? (long)(remainingMB / speedMBps) : 0;
|
||||||
|
|
||||||
try {
|
|
||||||
Thread.sleep(monitorDelayMs);
|
int barWidth = 30;
|
||||||
} catch (InterruptedException e) {
|
int filled = (int)(percent / 100.0 * barWidth);
|
||||||
System.out.println("Progress monitor interrupted.");
|
filled = Math.min(filled, barWidth);
|
||||||
return;
|
String bar = "=".repeat(filled) + (filled < barWidth ? ">" : "") + " ".repeat(Math.max(0, barWidth - filled - 1));
|
||||||
|
|
||||||
|
|
||||||
|
System.out.printf("\r[%-30s] %5.1f%% | %5.1f/%d MB | Speed: %.2f MB/s | ETA: %ds | Chunks: %d/%d ",
|
||||||
|
bar, percent, totalDownloadedMB, totalSizeMB,
|
||||||
|
speedMBps, etaSeconds,
|
||||||
|
completedChunks, chunks.size());
|
||||||
|
|
||||||
|
// System.out.printf(
|
||||||
|
// "Progress for %s: %.1f/%.1f MB (%.2f%%), completed chunks: %d/%d%n",
|
||||||
|
// fileName,
|
||||||
|
// totalDownloadedMB,
|
||||||
|
// (double) totalSizeMB,
|
||||||
|
// percent,
|
||||||
|
// completedChunks,
|
||||||
|
// chunks.size()
|
||||||
|
// );
|
||||||
|
|
||||||
|
|
||||||
|
if (completedChunks == chunks.size()) {
|
||||||
|
System.out.println("download completed!");
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
|
||||||
|
try {
|
||||||
|
Thread.sleep(monitorDelayMs);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
System.out.println("Progress monitor interrupted.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
fileName=movie.mkv
|
fileName=movie.mkv
|
||||||
totalSizeMB=120
|
totalSizeMB=120
|
||||||
chunkCount=6
|
chunkCount=10
|
||||||
minStepDelayMs=80
|
minStepDelayMs=200
|
||||||
maxStepDelayMs=200
|
maxStepDelayMs=600
|
||||||
minStepDownloadMB=2
|
minStepDownloadMB=.1
|
||||||
maxStepDownloadMB=6
|
maxStepDownloadMB=.4
|
||||||
Reference in New Issue
Block a user