How to use Java Lambda expression to create thread via Runnable function

 

Lambda expressions are introduced in Java 8. It represents one method interface called functional interface.
In this tutorial, we will see how to create a new Thread in Java using Lambda expression.

public class LambdaThreadDemo {
public static void main(String[] args) {
 
    // Implementing Runnable using old way
     Runnable runnable = new Runnable() {

     @Override
      public void run() {
            System.out.println("Old Thread name : "+ Thread.currentThread().getName());
         }
       };
    Thread thread1 = new Thread(runnable);
 
    // Implementing Runnable using Lambda Expression
     Runnable runnable_new = () -> { System.out.println("New Thread name : "+ Thread.currentThread().getName());
        };
     Thread thread_new = new Thread(runnable_new);
 
    // Start Threads
    thread1.start();
    thread_new.start();
   }
}

Output
Old Thread name : Thread-0
New Thread name : Thread-1

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s