Lambda Expressions with Runnable
What you'll learn: How to use lambda expressions to write cleaner, more concise Runnable implementations for threading tasks.
The Core Idea
You've already learned how to pass a Runnable to the Thread constructor. Traditionally, this required creating a class or an anonymous inner class. But since Runnable is a functional interface (it has exactly one abstract method: run()), you can use lambda expressions to simplify your code dramatically.
Instead of writing verbose anonymous classes, you can express the task inline with a short, readable lambda.
Traditional vs Lambda Approach
Traditional way (anonymous class):
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Task running in thread");
}
});
thread.start();
Lambda way:
Thread thread = new Thread(() -> {
System.out.println("Task running in thread");
});
thread.start();
Even simpler for single-statement tasks:
Thread thread = new Thread(() -> System.out.println("Task running in thread"));
thread.start();
Why This Works
The lambda () -> matches Runnable's signature: no parameters, no return value. The Java compiler understands that the Thread constructor expects a Runnable, so it automatically converts your lambda into one.
Real Example: Multiple Threads
for (int i = 1; i <= 3; i++) {
final int taskNumber = i;
Thread t = new Thread(() -> System.out.println("Task " + taskNumber + " executing"));
t.start();
}
Key Takeaway: Lambda expressions reduce Runnable boilerplate from several lines to just () -> yourCode, making concurrent task creation cleaner and more maintainable when tasks are simple.