Java thread lambda code example
Example 1: java anonymous thread lambda
public class LambdaThreadTest {
public static void main(String args[]) {
new Thread(() -> {
for(int i=1; i <= 5; i++) {
System.out.println("Child Thread: "+ i);
try {
Thread.sleep(500);
} catch(Exception e) {
e.printStackTrace();
}
}
}).start();
for(int j=1; j < 5; j++) {
System.out.println("Main Thread: "+ j);
try {
Thread.sleep(500);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Example 2: lambda expressions in java
A lambda expression is a short block
of code which takes in parameters
and returns a value. Lambda expressions
are similar to methods, but they do
not need a name and they can be
implemented right in the body of a method.
parameter -> expression
To use more than one parameter, wrap them in parentheses:
(parameter1, parameter2) -> expression
Example
Use a lamba expression in the ArrayList's
forEach() method to print every item in the list:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}