- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements