Can lambda expressions be used to create threads in Java?

Can lambda expressions be used to create threads in Java?

a) Yes, using the Runnable interface
b) Yes, using the Callable interface
c) No, lambda expressions cannot be used to create threads
d) Yes, using the Supplier interface

Answer:

a) Yes, using the Runnable interface

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top