(argument list) -> body
In this article, we see how Lambda expressions can simplify the creation of a new thread.Runnable task1 = new Runnable(){ @Override public void run(){ System.out.println("Task #1 is running"); } }; Thread thread1 = new Thread(task1); thread1.start();Or pass the anonymous class into the Thread’s constructor:
Thread thread1 = new Thread(new Runnable() { @Override public void run(){ System.out.println("Task #1 is running"); } }); thread1.start();
// Lambda Runnable Runnable task2 = () -> { System.out.println("Task #2 is running"); }; // start the thread new Thread(task2).start();It’s much more simple, isn’t it? By using Lambda expression, you don’t have to write the boilerplate code: declarations of the anonymous class and the run() method.And the following code snippet is for test program that demonstrates creating threads using both classic and Lambda approaches:
package net.codejava.lambda; /** * This simple program demonstrates how to use Lambda expressions to create * and run threads. * * @author www.codejava.net */ public class RunnableLambdaExample { public static void main(String[] args) { System.out.println(Thread.currentThread().getName() + ": RunnableTest"); // Anonymous Runnable Runnable task1 = new Runnable(){ @Override public void run(){ System.out.println(Thread.currentThread().getName() + " is running"); } }; // Passing a Runnable when creating a new thread Thread thread2 = new Thread(new Runnable() { @Override public void run(){ System.out.println(Thread.currentThread().getName() + " is running"); } }); // Lambda Runnable Runnable task3 = () -> { System.out.println(Thread.currentThread().getName() + " is running"); }; Thread thread1 = new Thread(task1); thread1.start(); thread2.start(); new Thread(task3).start(); } }
main: RunnableTest Thread-1 is running Thread-0 is running Thread-2 is runningRun #2:
main: RunnableTest Thread-1 is running Thread-2 is running Thread-0 is runningRelated Tutorials: