How to use Java Lambda expression to create thread via Runnable
- Details
- Written by Nam Ha Minh
- Last Updated on 18 August 2019   |   Print Email
(argument list) -> body
In this article, we see how Lambda expressions can simplify the creation of a new thread.1. Create a Java thread via Runnable using Classic Code
Before Java 8, we create and start a thread by creating an anonymous class that implements the Runnable interface, as shown in the following code: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();
2. Create a Java thread via Runnable using Lambda expression
With Lambda expressions come with Java 8, the above code can be re-written more concisely. For example:// 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(); } }
Run #1:
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:
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand Java Access Modifiers
- Understand how variables are passed in Java
- Understand Encapsulation in Java
Comments
What is there on the left side?
Have you install JDK 8 on your computer?