Commit ac3786f
committed
feat: run two infinite loops concurrently with Runnable and main thread
WHAT the code does:
- Defines MyRunnable implementing Runnable:
- run() contains an infinite loop printing incrementing numbers with "Hello".
- In PrintHelloSimulteneously main():
- Creates MyRunnable object.
- Wraps it in a Thread object and starts it.
- Meanwhile, the main thread runs its own infinite loop printing "World".
WHY this matters:
- Demonstrates concurrent execution of two infinite tasks: one in a worker thread, one in the main thread.
- Highlights the difference between implementing Runnable vs extending Thread.
- Shows how one program can have multiple independent execution flows interleaved by the scheduler.
- Provides a minimal example of thread concurrency where outputs intermix.
HOW it works:
1. MyRunnable.run() executes in a new thread after start() is called.
2. This worker thread repeatedly prints "Hello" with a counter.
3. Simultaneously, the main thread loops infinitely printing "World" with a counter.
4. The JVM scheduler interleaves the outputs, resulting in mixed "Hello" and "World" lines.
Key points:
- Runnable is often preferred over extending Thread because it decouples task logic from threading.
- Threads run simultaneously but output order is non-deterministic due to scheduling.
- This setup illustrates how the main thread can work alongside worker threads.
Short key: java-threads runnable-vs-thread infinite-loops concurrent-output.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 1a62fed commit ac3786f
1 file changed
+9
-27
lines changedLines changed: 9 additions & 27 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
4 | | - | |
5 | | - | |
| 1 | + | |
| 2 | + | |
6 | 3 | | |
7 | | - | |
8 | | - | |
| 4 | + | |
9 | 5 | | |
10 | 6 | | |
11 | 7 | | |
12 | 8 | | |
13 | | - | |
| 9 | + | |
14 | 10 | | |
15 | | - | |
| 11 | + | |
16 | 12 | | |
| 13 | + | |
17 | 14 | | |
18 | 15 | | |
19 | 16 | | |
| |||
23 | 20 | | |
24 | 21 | | |
25 | 22 | | |
26 | | - | |
27 | | - | |
28 | | - | |
29 | | - | |
30 | | - | |
31 | | - | |
32 | | - | |
33 | | - | |
34 | | - | |
35 | | - | |
36 | | - | |
37 | | - | |
38 | | - | |
| 23 | + | |
39 | 24 | | |
40 | | - | |
41 | 25 | | |
42 | 26 | | |
43 | 27 | | |
| |||
46 | 30 | | |
47 | 31 | | |
48 | 32 | | |
49 | | - | |
50 | | - | |
| 33 | + | |
51 | 34 | | |
52 | 35 | | |
53 | | - | |
54 | 36 | | |
55 | | - | |
| 37 | + | |
0 commit comments