Skip to content

Commit ba008b7

Browse files
committed
feat: add Thread vs Runnable demo (MyThread2 + PS) showing concurrent infinite loops and common pitfalls
WHAT the code does: - Adds `MyThread2` which extends `Thread` and prints `"nHello"` in an infinite loop from its `run()` method. - Adds class `PS` with: - Its own `run()` method (not a `Thread` or `Runnable`) that also prints `"nHello"` in an infinite loop (unused). - `main()` creates: - `MyThread2 t = new MyThread2();` - `MyRunnable t2 = new MyRunnable();` (assumed defined elsewhere) - A `Thread th = new Thread(t);` and starts `th`. - The main thread runs an infinite loop printing `"nWorld"`. - When executed, the program spawns a worker thread (`th`) and the main thread—both produce interleaved infinite console output. WHY this matters: - Demonstrates two common threading idioms in Java: subclassing `Thread` vs. using `Runnable`/wrapping a target in `Thread`. - Illustrates concurrency basics: multiple execution flows produce nondeterministic interleaved output. - Serves as an educational example of what *not* to do in production (infinite busy loops, uncontrolled printing, and confusing thread wiring). HOW it works (important details): 1. `MyThread2` defines the task by overriding `run()`—calling `t.start()` would spawn a native thread that executes `t.run()` asynchronously. 2. In `main()` code does `new Thread(t)` where `t` is itself a `Thread`: - `Thread(Thread target)` accepts a `Runnable`. Because `Thread` implements `Runnable`, this is legal but confusing: the *outer* thread `th` will call `t.run()` (the inner thread’s `run`), not `t.start()`. - That means `t` (the `MyThread2` instance) is never started as its own thread; instead its `run()` executes in the context of the *outer* thread `th`. 3. The main thread runs its own infinite loop printing `"World"`, so you get two infinitely-running loops in two threads (the outer thread and main). TIPS & GOTCHAS (practical, interview-friendly guidance): - Prefer `Runnable` (or `Callable`) for tasks and create `Thread` only to run them: `new Thread(new MyRunnable()).start();`. This avoids confusing nested-Thread semantics. - **Don’t pass a `Thread` object into `new Thread(...)`** — pass a `Runnable` target. Passing a `Thread` is legal (because Thread implements Runnable) but semantically misleading and can cause surprising behavior. - Avoid busy infinite loops that constantly print: they hog CPU and I/O and make programs unresponsive. Use `Thread.sleep()` or proper termination conditions. - If you need repeated background work, consider a scheduled executor (`ScheduledExecutorService`) or a thread pool (`Executors.newFixedThreadPool`) instead of raw threads. - Always name threads and consider `setDaemon(true)` for true background-only tasks that shouldn't keep the JVM alive. - For clean shutdown, provide a volatile flag (e.g., `volatile boolean running`) and check it in the loop so threads can terminate gracefully. - Beware of excessive console IO in loops — it becomes the bottleneck and hides scheduling semantics. CODE QUALITY NOTES: - `PS.run()` exists but isn’t used; if intent is to make `PS` a `Runnable`, implement `Runnable` or extend `Thread`. - Infinite loops without interruption handling are dangerous — consider catching `InterruptedException` and honouring interrupts. - Use consistent naming and follow Java class-name conventions (`PS`/`MyThread2` could be clearer). Short key: java-threads runnable-vs-thread infinite-loop avoid-passing-thread-to-thread concurrency-best-practices. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 44a2516 commit ba008b7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class MyThread2 extends Thread {
2+
public void run() {
3+
int i=1;
4+
5+
while(true) {
6+
System.out.println(i+"Hello");
7+
i++;
8+
}
9+
}
10+
}
11+
public class PS {
12+
public void run() {
13+
int i = 1;
14+
while (true) {
15+
System.out.println(i + "Hello");
16+
i++;
17+
}
18+
}
19+
public static void main(String[] args) {
20+
MyThread2 t=new MyThread2();
21+
22+
MyRunnable t2=new MyRunnable();
23+
24+
Thread th=new Thread(t);
25+
26+
th.start();
27+
28+
int i=1;
29+
while(true) {
30+
System.out.println(i+"World");
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)