This post shows how to implement Runnable interface as a lambda expression when you are creating a thread in Java. Since Runnable is a functional interface, Java 8 onward it can also be implemented as a lambda expression.
Refer Lambda expressions in Java 8 to know more about Java lambda expressions.
It is very common to implement the run() method of Runnable interface as an anonymous inner 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 in Java
public class RunnableLambda { public static void main(String[] args) { // Runnable using lambda new Thread(()->System.out.println("Runnable as Lambda expression")).start(); } }If you want to make it more obvious then you can also write it as below.
public class RunnableLambda { public static void main(String[] args) { Runnable r = ()->{System.out.println("Runnable as Lambda expression");}; // Passing runnable instance new Thread(r).start(); } }
That's all for this topic Java Lambda Expression Runnable Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
How does the Thread know that you are passing the object of Runnable and no other object type??
ReplyDeleteLambda supports "target typing" which infers the object type from the context in which it is used. Target type can be inferred from Method or constructor arguments.
Delete