43 lines
1.4 KiB
Markdown
43 lines
1.4 KiB
Markdown
**Question 1**
|
|
|
|
1- This is the output for the program:
|
|
``` Text
|
|
Calling run()
|
|
Running in: main
|
|
Calling start()
|
|
Running in: Thread-2
|
|
```
|
|
2- `t1.run()` will run the method from the thread that it is called from, which is `main` here. It does not create any new thread.
|
|
<br />
|
|
calling `t2.start()` will create a new thread (which is named `thread-2` here).
|
|
<hr />
|
|
|
|
**Question 2**
|
|
|
|
1- This is the output for the program:
|
|
``` Text
|
|
Main thread ends.
|
|
```
|
|
This happens because when the `main` thread is done and there is no other `User` thread running, then all of the `Daemon` threads will terminate.
|
|
|
|
2- If you remove that line, the thread becomes a `User` thread (the default).
|
|
|
|
*Behavior*:
|
|
The program will print "Main thread ends."
|
|
However, the JVM will not exit.
|
|
It will keep running for approximately 10 seconds until the DaemonRunnable finishes all 20 iterations of its loop.
|
|
Only after the run() method of that thread completes will the JVM shut down.
|
|
|
|
3- Some real-life use cases of daemon threads are background tasks that need to be automatically closed after the main application shuts down like `garbage collectors` and `spell checkers` or `auto saves`.
|
|
<hr />
|
|
|
|
**Question 3**
|
|
|
|
1- This is the output for the program:
|
|
``` Text
|
|
Thread is running using a ...!
|
|
```
|
|
|
|
2- It is called a `lambda expression`.
|
|
|
|
3- This is much more concise. But lacks the maintainability which class method provides. |