This post shows how to write runnable as a lambda expression. Since Runnable is a functional interface, starting Java 8 it can also be implemented as a lambda expression.
- Refer Lambda expressions in Java 8 to know more about lambda expression.
It is very common to implement the run method of runnable interface as an anonymous class, as shown in the following code.
Runnable as an anonymous class
public class RunnableIC {
public static void main(String[] args) {
// Runnable using anonymous class
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Runnable as anonymous class");
}
}).start();
}
}
From Java 8 same can be done with lambda expression in fewer lines increasing readability, as shown in the following code.
Runnable as a lambda expression
public class RunnableLambda {
public static void main(String[] args) {
// Runnable using lambda
New Thread(()->System.out.println("Runnable as Lambda expression")).start();
}
}
That's all for this topic Lambda Expression Runnable example. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -