Files
2026-06-08 17:03:30 +03:30

69 lines
1.9 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## 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 shouldnt 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 dont need to create a separate class anymore; you just pass the logic directly as a lambda. Its cleaner and less boilerplate code.