Commit 63cb249
committed
feat(PackageWithLambdaExpression): add Main using Runnable with lambda
What
- Added Main class in package PackageWithLambdaExpression.
- Demonstrates creating a Runnable instance via lambda instead of a separate class.
- Runnable lambda prints "Hello i" from 1 to 9 in a loop.
- Runnable passed into Thread constructor.
- Invoked childthread.run() to execute run() logic.
Why
- Shows how lambdas simplify Runnable implementation by eliminating boilerplate classes.
- Provides a concise alternative to the explicit Runnable class implementation shown earlier.
- Educational example bridging functional programming (lambda) with concurrency (Runnable/Thread).
How
- Defined Runnable using lambda () -> { loop body }.
- Loop iterates from i=1 to i<10 (since i<+10 is equivalent to i<10).
- Printed "Hello i" for each iteration.
- Created Thread childthread with runnable.
- Called childthread.run().
Logic
- Inputs: none; loop controlled internally.
- Outputs: "Hello 1" through "Hello 9" printed to stdout.
- Flow:
1. Lambda assigned to Runnable.
2. Thread constructed with Runnable.
3. childthread.run() directly calls run() on current thread.
4. Loop executes printing messages.
- Edge cases:
- Using run() executes on main thread; for true concurrency, start() must be used.
- Loop condition with `<+10` is redundant but still functions correctly.
- Complexity / performance: O(n) with n=9 iterations.
- Concurrency / thread-safety:
- Code currently runs sequentially; no real multi-threading occurs.
- If start() were used, it would run on a separate thread safely since lambda is stateless.
- Error handling:
- No exceptions expected.
Real-life applications
- Lambdas provide compact thread creation, e.g., background tasks or simple workers.
- Common in server code, GUI event handling, or scheduled jobs.
- Ideal for lightweight tasks without needing a dedicated Runnable class.
Notes
- Replace run() with start() to execute on a new thread instead of the main thread.
- Demonstrates functional style of thread creation in modern Java.
- Using lambdas keeps code short, readable, and avoids boilerplate.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 4877bde commit 63cb249
File tree
1 file changed
+14
-0
lines changed- Java 8 Crash Course/Lambda Expression/Thread Using Lambda Expression/src/PackageWithLambdaExpression
1 file changed
+14
-0
lines changedLines changed: 14 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 | + | |
| 13 | + | |
| 14 | + | |
0 commit comments