Tuesday, February 12, 2019

Java Lambda Expression Runnable Example

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.

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

  1. Java Lambda Expression Comparator Example
  2. Java Lambda Expression Callable Example
  3. Functional Interface Annotation in Java
  4. How to Fix The Target Type of This Expression Must be a Functional Interface Error
  5. Java Lambda Expressions Interview Questions

You may also like-

  1. Producer-Consumer Java Program Using ArrayBlockingQueue
  2. Print Odd-Even Numbers Using Threads And wait-notify - Java Program
  3. Converting int to String - Java Program
  4. Synchronization in Java Multi-Threading
  5. BlockingDeque in Java Concurrency
  6. Polymorphism in Java
  7. Optional class in Java 8
  8. Autowiring using XML configuration in Spring