Can lambda expressions be used to create threads in Java?
Answer:
Explanation:
Lambda expressions can be used to create threads in Java by passing them to the Runnable
interface. The Runnable
interface is a functional interface with a single abstract method, run()
, which makes it a perfect candidate for lambda expressions. Here is an example:
Thread thread = new Thread(() -> System.out.println("Thread is running")); thread.start();
In this example, the lambda expression () -> System.out.println("Thread is running")
is passed to the Thread
constructor, creating a new thread that prints a message when it runs. This demonstrates the power and simplicity of using lambda expressions to create and manage threads in Java.
By using lambda expressions with the Runnable
interface, developers can write multithreaded code that is more concise and easier to understand. This is particularly beneficial in applications where threads are frequently created and managed, such as in server-side processing or real-time systems.