64 lines
2.2 KiB
Markdown
64 lines
2.2 KiB
Markdown
## Answers to Theoretical Questions
|
||
|
||
### 1. `start()` vs `run()`
|
||
|
||
**Output:**
|
||
```
|
||
Calling run()
|
||
Running in: main
|
||
Calling start()
|
||
Running in: Thread-2
|
||
```
|
||
|
||
- When we call `run()` directly, it's just a normal method call.
|
||
No new thread is created – everything happens inside the current thread (here `main`).
|
||
That's why the printed thread name is `main`.
|
||
|
||
- Calling `start()` actually creates a brand new thread and then runs `run()` inside that new thread.
|
||
So the output shows that `Thread-2` is the one executing the code.
|
||
|
||
- The main difference:
|
||
`run()` → synchronous, runs in the caller thread.
|
||
`start()` → asynchronous, spawns a separate thread and runs `run()` there.
|
||
|
||
---
|
||
|
||
### 2. Daemon Threads
|
||
|
||
**Program output (when `setDaemon(true)` is used):**
|
||
```
|
||
Main thread ends.
|
||
Daemon thread running...
|
||
```
|
||
(Only a few lines might appear before the program exits.)
|
||
|
||
- By marking the thread as a daemon, we tell the JVM: *"This thread is doing background work – don't wait for it."*
|
||
As soon as all **user threads** finish, the JVM shuts down, even if daemon threads are still running.
|
||
Here `main` is a user thread, so after it prints its message and ends, the program terminates quickly.
|
||
|
||
- If we **remove** `thread.setDaemon(true)`, the thread becomes a normal user thread.
|
||
Then the JVM will wait for it to finish all 20 iterations before exiting.
|
||
We'd see `"Daemon thread running..."` printed 20 times.
|
||
|
||
- Real‑life examples of daemon threads:
|
||
- The **garbage collector** in Java – runs in the background but won't stop the JVM from closing.
|
||
- **Auto‑save** in a text editor – saves periodically but shouldn't block the program from closing.
|
||
|
||
---
|
||
|
||
### 3. A shorter way to create threads
|
||
|
||
**Output:**
|
||
```
|
||
Thread is running using a ...!
|
||
```
|
||
|
||
- The `() -> { ... }` part is a **lambda expression**.
|
||
It's a compact way to write an anonymous function.
|
||
|
||
- Instead of creating a whole new class that implements `Runnable` (or extending `Thread`), we can just pass the body of `run()` directly inside `new Thread(...)`.
|
||
This makes the code much shorter and easier to read, especially for one‑off tasks.
|
||
|
||
- Lambdas are perfect for simple jobs, but if the task is complex or needs to be reused, a separate class might be better.
|
||
|