Commit f082dc0
committed
feat: add Thread2 demo with sleep and join for sequential execution
WHAT the code does:
- Defines Thread2 extending Thread.
- Overrides run():
- Loops from 1 to 5, sleeping 5 seconds between each iteration.
- Prints the counter and a final message ("Thread is running.....").
- In main():
- Creates a Thread2 object.
- Starts the thread with start().
- Calls join() to ensure main waits until t2 finishes.
WHY this matters:
- Demonstrates thread lifecycle with controlled execution order.
- join() ensures the main thread does not exit before the child thread completes.
- Thread.sleep() introduces artificial delay to visualize scheduling and thread control.
HOW it works:
1. t2.start() → JVM schedules run() in a separate thread.
2. run() executes:
- For each iteration, sleeps for 5s (TIMED_WAITING state).
- After waking, prints the current counter.
3. After loop, prints completion message.
4. main thread waits due to join(), preventing premature termination.
Use-case:
- Useful when you want tasks to complete in strict sequence.
- Demonstrates the difference between concurrent execution and forced synchronization with join().
Short key: java-threads sleep-join sequential-demo.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 09f8fac commit f082dc0
1 file changed
+8
-11
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
4 | | - | |
5 | | - | |
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
6 | 5 | | |
7 | | - | |
| 6 | + | |
8 | 7 | | |
9 | 8 | | |
10 | | - | |
11 | | - | |
| 9 | + | |
12 | 10 | | |
13 | 11 | | |
14 | 12 | | |
15 | 13 | | |
16 | 14 | | |
17 | 15 | | |
18 | | - | |
19 | | - | |
| 16 | + | |
20 | 17 | | |
21 | 18 | | |
22 | 19 | | |
23 | 20 | | |
24 | | - | |
| 21 | + | |
0 commit comments