Java Lambda Expression Runnable Example

In this post, we will see how to use Lambda expression to implement the Runnable interface with an example.

Runnable Interface Example using Anonymous Class

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time.
public class RunnableExampleUsingAnonymousClass {

    public static void main(final String[] args) {
        System.out.println(" main thread started : " + Thread.currentThread().getName());

        System.out.println("Creating Runnable...");

        final Runnable runnable = new Runnable() {
   
             @Override
             public void run() {
                 System.out.println("Inside : " + Thread.currentThread().getName());
    
             }
        }; 

        System.out.println("Creating Thread...");
        final Thread thread = new Thread(runnable);

        System.out.println("Starting Thread...");
        thread.start();
        
        System.out.println(" main thread ended : " + Thread.currentThread().getName());
    }
}
Output:
 main thread started : main
Creating Runnable...
Creating Thread...
Starting Thread...
 main thread ended : main
Inside  : Thread-0

Runnable Interface Example Using Lambda Expression

The above example can be made even shorter by using Java 8 Lambda Expressions -
public class RunnableExampleUsingLambda {

    public static void main(final String[] args) {
        System.out.println(" main thread started : " + Thread.currentThread().getName());

        System.out.println("Creating Runnable...");

        final Runnable runnable = () -> System.out.println("Inside  : " + Thread.currentThread().getName()); 

        System.out.println("Creating Thread...");
        final Thread thread = new Thread(runnable);

        System.out.println("Starting Thread...");
        thread.start();
        
        System.out.println(" main thread ended : " + Thread.currentThread().getName());
    }
}
Output:
Creating Runnable...
Creating Thread...
Starting Thread...
 main thread ended : main
Inside  : Thread-0

References


Comments