Skip to content

Commit 4877bde

Browse files
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 a55b416 commit 4877bde

File tree

1 file changed

+10
-0
lines changed
  • Java 8 Crash Course/Lambda Expression/Thread Using Lambda Expression/src/Package

1 file changed

+10
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package Package;
2+
3+
public class MyClass implements Runnable {
4+
@Override
5+
public void run() {
6+
for(int i=1; i<+10; i++) {
7+
System.out.println("Hello "+i);
8+
}
9+
}
10+
}

0 commit comments

Comments
 (0)