Lambda Expressions added in Java 8 help us to write functional programming.
Here we are going to create a Thread using a Runnable Interface.
From Java 8, a Runnable interface is called as a Functional Interface and has only one abstract method named run()
Using Lambda Expressions we can directly write the implementation for the abstract method of the interface in Java. Otherwise, we need to override the run method and write the implementation by implementing the Runnable interface in earlier versions of Java.
Thread without lambda expression
Runnable runnable = new Runnable() {
public void run() {
//implementation logic
}
};
Thread thread1 = new Thread(runnable);
thread1.start();
How the above code is simplified with Lambda Expression
Thread thread1 = new Thread(() -> {
// your implementation logic
});
thread1.start();
or without the reference variable thread1,
new Thread(() -> {//implementation logic}).start();
Lambda Expression syntax for run() method
() -> {
//code
}
//public void run() {} is represented as () -> {}
() - run method has no arguments. so denote it with the empty parentheses.
-> - called as Arrow token
{} - is the lambda expression body. The code should be written here.
Thread with lambda expression
Using Lambda expression, there is no need to write the new Runnable() and run() method. We can directly write the implementation using the lambda expression without overriding the run() method.
LambdaThreadExample.java
In this class, we write two threads namely Thread-0 (aka child thread) and the main thread. Thread-0 is written using Lambda Expressions. Thread-0 prints odd numbers and the main thread prints even numbers.
Instead of the run() method, it is represented using a lambda expression () ->
public class LambdaThreadExample {
public static void main(String args[]) {
int oddNums[] = { 1, 3, 5, 7 };
int evenNums[] = { 2, 4, 6 };
new Thread(() -> {
for (int odd : oddNums) {
System.out.println(Thread.currentThread().getName() + " prints: " + odd);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
for (int even : evenNums) {
System.out.println(Thread.currentThread().getName() + " thread prints: " + even);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Output
main thread prints: 2
Thread-0 prints: 1
main thread prints: 4
Thread-0 prints: 3
Thread-0 prints: 5
main thread prints: 6
Thread-0 prints: 7
From the output, the order of the thread execution is not guaranteed in a multithreaded environment. Here main thread runs faster than the Thread-0, but it is not always the same case. When you run it again the execution order may differ.