In Java, you can create a Thread using Lambda expression by leveraging ‘Runnable’ functional interface. It’s very simple and straight-forward approach to create thread by defining run method of the interface. How to create Thread using Lambda expression in Java?
Simplest way to Create Thread using Lambda Expression in Java 8 Share on X
Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /** * Using Java 8, Create a Thread using Lambda Expression * @author Deepak Verma * */ public class Create_Thread_using_Lambda_Expression_in_Java8 { public static void main(String[] args) { // Using lambda expression to create a thread Thread myThread = new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println("Thread is running: " + i); } }); // Start the thread myThread.start(); } } |
Output:
1 2 3 4 5 | Thread is running: 0 Thread is running: 1 Thread is running: 2 Thread is running: 3 Thread is running: 4 |
find first non repeated character in a string using Java 8
In this example:
- We create a
Thread
object and pass a lambda expression as the argument to theThread
constructor. The lambda expression represents therun()
method of theRunnable
interface. - Inside the lambda expression, we define the code that the thread will execute. In this case, it’s a simple loop printing a message.
The above code demonstrates how to create a thread using lambda expressions in a concise and expressive manner. Note that lambda expressions are particularly useful when you need to provide a simple implementation for functional interfaces like Runnable
or Callable
.
Simplest way to create Thread using Lambda in Java 8..!!! Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: