69 lines
1.9 KiB
Markdown
69 lines
1.9 KiB
Markdown
## Question 1:
|
||
|
||
Output
|
||
```bash
|
||
Calling run()
|
||
Running in: main
|
||
Calling start()
|
||
Running in: Thread-2
|
||
```
|
||
|
||
When we call `t1.run()`, we are just calling a method in the current thread(the main thread).
|
||
No extra thread is created.
|
||
|
||
But if we call `t2.start()`, the code runs in a separate thread and use multithreading.
|
||
|
||
## Question 2:
|
||
|
||
Output:
|
||
```bash
|
||
Main thread ends.
|
||
Daemon thread running...
|
||
```
|
||
|
||
- The main thread finishes immediately and the other thread is stopped right after because it's a daemon thread.
|
||
|
||
|
||
- If we remove `thread.setDaemon(true)`, the thread won't be a daemon anymore. So when the main thread finishes, the other thread will continue and the output would be :
|
||
|
||
```bash
|
||
Main thread ends.
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
Daemon thread running...
|
||
```
|
||
|
||
- Background Tasks: Tasks that shouldn’t block the application from shutting down.
|
||
Examples:
|
||
Garbage Collection: Memory management.
|
||
Auto-save: Periodically saving temporary drafts.
|
||
Monitoring/Heartbeats: Checking system health or connection status in the background.
|
||
|
||
|
||
## Question 3:
|
||
|
||
Output:
|
||
```bash
|
||
Thread is running using a ...!
|
||
```
|
||
|
||
- **Syntax**: This is a Lambda Expression, a shortcut in to write code blocks (functions) concisely.
|
||
- **Difference**: Your code is just a shorter version of the standard `implements Runnable` approach.
|
||
You don’t need to create a separate class anymore; you just pass the logic directly as a lambda. It’s cleaner and less boilerplate code. |