Commit 562bac0
committed
feat: demonstrate daemon threads and join with main thread reference
WHAT the code does:
- Defines `MyThreadIMP` extending `Thread`:
- run() starts a counter and continuously prints incrementing numbers in an infinite loop.
- In `ThreadNewMethods.main()`:
- Creates a `MyThreadIMP` instance.
- Marks it as a daemon thread with `setDaemon(true)`.
- Starts the thread, causing it to print numbers indefinitely.
- Retrieves a reference to the main thread (`Thread.currentThread()`).
- Calls `mainThread.join()`, making the main thread wait on itself (a logical deadlock scenario).
WHY this matters:
- Demonstrates the concept of **daemon threads**:
- Daemon threads run in the background and automatically terminate when all non-daemon (user) threads finish.
- They are often used for background tasks like garbage collection or monitoring.
- Shows usage of `Thread.join()`, which normally makes one thread wait for another to complete.
- Highlights a misuse: calling `join()` on the main thread itself causes it to wait forever, blocking program termination unless daemon threads are involved.
HOW it works:
1. `t.setDaemon(true)` ensures the worker thread does not prevent JVM termination.
2. `t.start()` launches the daemon thread printing numbers.
3. `mainThread.join()` causes the main thread to wait indefinitely for itself, so the program never proceeds further.
4. Since only a daemon thread (`t`) remains running, JVM will eventually terminate once the main thread exits or is forcibly stopped.
Key points & gotchas:
- A daemon thread is dependent on user threads. When no user threads are alive, JVM stops all daemons.
- Setting a thread as daemon must be done before `start()`. Calling it after will throw `IllegalThreadStateException`.
- `mainThread.join()` is a trap: the main thread will never complete because it is waiting on itself.
- Proper usage of `join()` is for one thread to wait for another thread to finish.
- Infinite loops in daemon threads terminate abruptly once the JVM exits, which may leave tasks incomplete.
Real-world analogy:
- Daemon threads are like janitors in a building: they keep working in the background but leave immediately when everyone else (user threads) goes home.
Short key: java-threads daemon-vs-user join-method deadlock-pitfall.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 30c8861 commit 562bac0
1 file changed
+9
-10
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
4 | | - | |
| 1 | + | |
| 2 | + | |
5 | 3 | | |
6 | | - | |
7 | | - | |
| 4 | + | |
| 5 | + | |
8 | 6 | | |
9 | 7 | | |
10 | 8 | | |
11 | 9 | | |
| 10 | + | |
12 | 11 | | |
13 | | - | |
14 | | - | |
| 12 | + | |
15 | 13 | | |
16 | 14 | | |
17 | 15 | | |
18 | | - | |
| 16 | + | |
| 17 | + | |
19 | 18 | | |
20 | 19 | | |
21 | 20 | | |
| |||
25 | 24 | | |
26 | 25 | | |
27 | 26 | | |
28 | | - | |
| 27 | + | |
0 commit comments