- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a thread using lambda expressions in Java?
The lambda expressions are introduced in Java 8. It is one of the most popular features of Java 8 and brings functional programming capabilities to Java. By using a lambda expression, we can directly write the implementation for a method in Java.
In the below program, we can create a thread by implementing the Runnable interface using lamda expression. While using the lambda expressions, we can skip the new Runnable() and run() method because the compiler knows that Thread object takes a Runnable object and that contains only one method run() that takes no argument.
Example
public class LambdaThreadTest { public static void main(String args[]) { // Child thread new Thread(() -> { // Lambda Expression for(int i=1; i <= 5; i++) { System.out.println("Child Thread: "+ i); try { Thread.sleep(500); } catch(Exception e) { e.printStackTrace(); } } }).start(); // Main Thead for(int j=1; j < 5; j++) { System.out.println("Main Thread: "+ j); try { Thread.sleep(500); } catch(Exception e) { e.printStackTrace(); } } } }
Output
Main Thread: 1 Child Thread: 1 Child Thread: 2 Main Thread: 2 Main Thread: 3 Child Thread: 3 Main Thread: 4 Child Thread: 4 Child Thread: 5
- Related Articles
- How to create a thread using method reference in Java?\n
- How to implement the listeners using lambda expressions in Java?
- How to debug lambda expressions in Java?
- How to create a thread in Java
- How to create a thread by using anonymous class in Java?
- What are the advantages of Lambda Expressions in Java?\n
- How to populate a Map using a lambda expression in Java?\n
- What are the scoping rules for lambda expressions in Java?\n
- How to implement JavaFX event handling using lambda in Java? \n
- How to handle an exception using lambda expression in Java?\n
- Are lambda expressions objects in Java?
- What are lambda expressions in Java?
- How to create a thread in JShell in Java 9?
- Java Program to initialize a HashMap with Lambda Expressions
- What are lambda expressions and how to use them in Java?

Advertisements