Commit a55b416
committed
feat(Package): add Main and MyClass demonstrating Runnable with thread execution
What
- Added MyClass implementing Runnable:
- Overrides run() to print "Hello i" from 1 to 9.
- Added Main class:
- Creates MyClass instance.
- Demonstrates threading by constructing Thread with MyClass.
- Calls childthread.run() to execute run() logic.
Why
- Illustrates how to implement the Runnable interface and pass it to a Thread.
- Serves as an educational example of Java’s multithreading basics.
- Demonstrates the difference between main thread and additional threads (though run() is used instead of start()).
How
- Implemented Runnable in MyClass.
- In run(), loop prints sequential messages to stdout.
- In Main, instantiated MyClass and wrapped it in a Thread.
- Invoked childthread.run() to call run() method.
Logic
- Inputs: none (loop controlled inside run()).
- Outputs: "Hello 1" through "Hello 9" printed to stdout.
- Flow:
1. Main thread executes main().
2. MyClass instance created.
3. Thread constructed with MyClass.
4. childthread.run() directly calls run(), executing on main thread.
5. Loop prints 9 messages.
- Edge cases:
- Using run() executes on current thread, not a new one. To create a true child thread, start() must be called instead.
- Loop condition i<+10 is equivalent to i<10; still works as expected.
- Complexity / performance: O(n) with n=9 iterations; trivial.
- Concurrency / thread-safety:
- Currently no real concurrency since run() is invoked directly.
- If start() were used, run() would execute on a separate thread.
- Error handling:
- No exceptions expected.
Real-life applications
- Runnable is the standard way to encapsulate logic for execution in a thread.
- Common for background tasks, parallel computation, or offloading work from main thread.
- This example is suitable for teaching thread basics and pitfalls (run vs start).
Notes
- To actually execute in parallel, replace childthread.run() with childthread.start().
- Loop condition could be simplified to i < 10 for clarity.
- Example demonstrates mechanics of Runnable but not true multithreading yet.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 51210fa commit a55b416
File tree
1 file changed
+12
-0
lines changed- Java 8 Crash Course/Lambda Expression/Thread Using Lambda Expression/src/Package
1 file changed
+12
-0
lines changedLines changed: 12 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
0 commit comments