I am using jdk-11 for this tutorial.
We are going to use lambda functions to create a thread in java. In this tutorial, we will implement Runnable interface.
Our lambda implementation will print numbers from the range 1 to 10.
Step 1 :- implement Runnable interface
Runnable runThroughLambda = () -> IntStream.rangeClosed(1, 10) .forEach(System.out::println);
In above code, I created a stream of integers from 1 to 10. And then, the integers are Printed it to console.
Step 2 :- Pass the implementation of runnable created above to create a thread object.
Thread threadUsesLambda = new Thread(runThroughLambda);
We created a thread object, and we passed the lambda in it’s constructor.
We could have done this too.
Thread threadUsesLambda = new Thread(() -> IntStream.rangeClosed(1, 10) .forEach(System.out::println));
We can also pass lambda directly in the constructor, but defining separate variable makes it more readable.
Step 3 :- Now, we are going to start the thread.
threadUsesLambda.start();
OutPut :-
1 2 3 4 5 6 7 8 9 10
OR
We can put entire code in one line, and save space. 🙂
new Thread(() -> IntStream.rangeClosed(1, 10).forEach(System.out::println)).start();
OR
We can format the code to make it more readable.
new Thread(() -> IntStream.rangeClosed(1, 10) .forEach(System.out::println)) .start();
But, it is always good to use variables to isolate small parts to make it more readable and maintainable.
Complete Code :-
package com.threading; import java.util.stream.IntStream; public class LambdaRunnable { public static void main(String[] args) { Runnable runThroughLambda = () -> IntStream.rangeClosed(1, 10) .forEach(System.out::println); Thread threadUsesLambda = new Thread(runThroughLambda); threadUsesLambda.start(); } }