Sunday, September 24, 2017

Lambda (Java 8) - How to use Runnable interface

In this article, I'm going to explain the way we can use lambda to implement the Runnable interface.

General scenario is below:
  
   ...
   Thread myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Printed inside runnable");
            System.out.println(Thread.currentThread().getId());
        }
   });
   myThread.start();
   ...
Below is the code segment, same above implementation with lambda.
   ...
        Thread myLambdaThread = new Thread(() -> {
            System.out.println("printed inside the lambda expression");
            System.out.println("Thread Id: " + Thread.currentThread().getId());
        });

        myLambdaThread.start();
   ...


  • Empty parentheses: because run() method doesn't allow any arguments.
  • If there is more than one line of the implementation, we need to write the implementation inside the curly brackets.


Note: Runable interface only one method call run(), so we can write lambda expression. If there is more than one method declaration inside a interface, we cannot write lambda expression.

Enjoy..!!

No comments:

Post a Comment