Skip to content

Commit ac3786f

Browse files
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

File tree

1 file changed

+9
-27
lines changed

1 file changed

+9
-27
lines changed
Lines changed: 9 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,16 @@
1-
2-
/*class MyThread extends Thread
3-
{
4-
public void run()
5-
{
1+
class MyRunnable implements Runnable {
2+
public void run() {
63
int i=1;
7-
while(true)
8-
{
4+
while(true) {
95
System.out.println(i+"Hello");
106
i++;
117
}
128
}
13-
}*/
9+
}
1410

15-
class MyRunnable implements Runnable
11+
public class PrintHelloSimulteneously //implements Runnable //extends Thread.
1612
{
13+
/*
1714
public void run()
1815
{
1916
int i=1;
@@ -23,21 +20,8 @@ public void run()
2320
i++;
2421
}
2522
}
26-
}
27-
public class PrintHelloSimulteneously //implements Runnable //extends Thread
28-
{
29-
/*public void run()
30-
{
31-
int i=1;
32-
while(true)
33-
{
34-
System.out.println(i+"Hello");
35-
i++;
36-
}
37-
}*/
38-
23+
*/
3924
public static void main(String[] args) {
40-
4125
//MyThread t=new MyThread();
4226
//ThreadTest t=new ThreadTest();
4327
MyRunnable t=new MyRunnable();
@@ -46,10 +30,8 @@ public static void main(String[] args) {
4630
th.start();
4731

4832
int i=1;
49-
while(true)
50-
{
33+
while(true) {
5134
System.out.println(i+"World");
5235
}
53-
5436
}
55-
}
37+
}

0 commit comments

Comments
 (0)