Skip to content

Commit 63cb249

Browse files
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 changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package PackageWithLambdaExpression;
2+
3+
public class Main {
4+
public static void main(String[] args) {
5+
/* functional interface acts as a type for lambda expression. */
6+
Runnable runnable = () -> {
7+
for(int i=1; i<+10; i++) {
8+
System.out.println("Hello "+i);
9+
}
10+
};
11+
Thread childthread = new Thread(runnable);
12+
childthread.run();
13+
}
14+
}

0 commit comments

Comments
 (0)