How to implement the Runnable interface using lambda expression in Java?


The Runnable interface is a functional interface defined in java.lang package. This interface contains a single abstract method, run() with no arguments. When an object of a class implementing this interface used to create a thread, then run() method has invoked in a thread that executes separately.

Syntax

@FunctionalInterface
public interface Runnable {
 void run();
}

In the below example, we can implement a Runnable interface by using an anonymous class and lambda expression.

Example

public class RunnableLambdaTest {
   public static void main(String[] args) {
      Runnable r1 = new Runnable() {
         @Override
         public void run() { // anonymous class
            System.out.println("Runnable with Anonymous Class");
         }
      };
      Runnable r2 = () -> {   // lambda expression
         System.out.println("Runnable with Lambda Expression");
      };
      new Thread(r1).start();
      new Thread(r2).start();
   }
}

Output

Runnable with Anonymous Class
Runnable with Lambda Expression

Updated on: 13-Jul-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements