Monday, 9 May 2016

Lambda Expression Runnable example

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.

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

  1. Overview of lambda expressions
  2. Functional interfaces & lambda expression
  3. Functional interface annotation in Java 8
  4. Lambda Expression Comparator example
  5. Count total number of times each character appears in a String
  6. How to sort arraylist of custom objects in Java

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment