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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 09-Jan-2020 12:07:11
Advertisements