Java Create Thread with Lambda Expression

Java Thread Examples


Let's first see the example of creating Thread without lambda expression.

Runnable Interface Example using Anonymous Class

In the following example, we are using the Runnable interface with Anonymous class syntax to create the Thread:
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

Create Thread (Runnable Interface) with 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

Comments