Wednesday, May 4, 2022

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.

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

  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 And Answers

You may also like-

  1. Producer-Consumer Java Program Using ArrayBlockingQueue
  2. Printing Numbers in Sequence Using Threads Java Program
  3. Convert int to String in Java
  4. Synchronization in Java - Synchronized Method And Block
  5. Java BlockingDeque With Examples
  6. Polymorphism in Java
  7. Optional Class in Java With Examples
  8. Autowiring using XML configuration in Spring

2 comments:

  1. How does the Thread know that you are passing the object of Runnable and no other object type??

    ReplyDelete
    Replies
    1. Lambda 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