Lambda Expressions for Runnable
What you'll learn: How to use lambda syntax to create concise, readable Runnable instances for simple threaded tasks.
The Core Idea
Since Runnable is a functional interface (it has exactly one abstract method: run()), you can replace verbose anonymous class syntax with clean lambda expressions. Instead of writing several lines to define what a thread should do, you can express the same logic in a single, readable line.
Why This Matters
Traditional Runnable creation requires boilerplate code. Lambda expressions eliminate this ceremony, making your concurrent code easier to write and understand. When you're spinning up threads for simple tasks, lambdas keep your code focused on what the thread does, not how you're defining it.
The Syntax
// Verbose way you already know:
Thread oldStyle = new Thread(new Runnable() {
public void run() {
System.out.println("Task running");
}
});
// Lambda way - clean and concise:
Thread newStyle = new Thread(() -> {
System.out.println("Task running");
});
// For single statements, even simpler:
Thread oneLinー = new Thread(() -> System.out.println("Task running"));
Think of It This Way
A lambda is like giving someone verbal instructions instead of handing them a written manual. Both accomplish the goal, but one is more direct. The lambda says, "Here's what to do," without the formality of creating a full class structure.
When to Use Lambdas
Lambdas shine for simple, short-lived tasks. If your run() method is just a few lines, lambda syntax keeps everything readable and in one place.
Key Takeaway: Lambda expressions transform Runnable creation from a multi-line ceremony into a concise, inline task definition, making concurrent code cleaner and more maintainable.