complete theoretical part
This commit is contained in:
@@ -0,0 +1,57 @@
|
|||||||
|
## Theoretical Questions
|
||||||
|
### 1. `start()` vs `run()`
|
||||||
|
- What output do you get from the program? Why?
|
||||||
|
```
|
||||||
|
Calling run()
|
||||||
|
Running in: main
|
||||||
|
Calling start()
|
||||||
|
Running in: Thread-2
|
||||||
|
```
|
||||||
|
→ When `t1.run()` is called directly, we're calling the `run()` method like a
|
||||||
|
normal method and no new thread is created. The `run()` method is executed on the
|
||||||
|
current thread (main); so `Thread.currentThread().getName()` returns "main".
|
||||||
|
<br/> When `t2.start()` is called: `start()` creates a new thread named "Thread-2".
|
||||||
|
The new thread automatically calls `run()` so `Thread.currentThread().getName()` returns "Thread-2".
|
||||||
|
|
||||||
|
- What’s the difference in behavior between calling `start()` and `run()`?
|
||||||
|
→ `start()`: creates a new thread and is executed on a new thread.
|
||||||
|
`run()`: method doesn't create new thread and is executed on the current thread.
|
||||||
|
|
||||||
|
### 2. Daemon Threads
|
||||||
|
|
||||||
|
- What output do you get from the program? Why?
|
||||||
|
```
|
||||||
|
Main thread ends.
|
||||||
|
Daemon thread running...
|
||||||
|
```
|
||||||
|
→ The thread is set as a Daemon thread. The main thread ends immediately after
|
||||||
|
printing "Main thread ends." and the JVM exits without waiting for the daemon thread to complete its loop.
|
||||||
|
|
||||||
|
- What happens if you remove `thread.setDaemon(true)`?
|
||||||
|
|
||||||
|
→ The thread becomes a user thread. The main thread still ends,
|
||||||
|
but the JVM will not exit because there is still a live user thread.
|
||||||
|
The program will print all 20 "Daemon thread running..." messages.
|
||||||
|
- What are some real-life use cases of daemon threads?
|
||||||
|
|
||||||
|
→ Spell Checker / Grammar Checker in Word.
|
||||||
|
|
||||||
|
### 3. A shorter way to create threads
|
||||||
|
|
||||||
|
- What output do you get from the program?
|
||||||
|
```
|
||||||
|
Thread is running using a ...!
|
||||||
|
```
|
||||||
|
- What is the `() -> { ... }` syntax called?
|
||||||
|
|
||||||
|
→ lambda expression
|
||||||
|
|
||||||
|
- How is this code different from creating a class that extends `Thread` or implements `Runnable`?
|
||||||
|
|
||||||
|
→ The code uses a lambda expression to define the `run()` method inline.
|
||||||
|
When you extend `Thread`, you must create a separate subclass, override the `run()` method,
|
||||||
|
and then instantiate that subclass. This gives you the ability to add
|
||||||
|
new fields or methods to your thread class, but it also means you cannot extend any other class.
|
||||||
|
When you implement `Runnable` using an anonymous class (the old way before lambdas), you write:
|
||||||
|
|
||||||
|
`new Runnable() { public void run() { ... } }`.
|
||||||
Reference in New Issue
Block a user