Use Case: Thread Runnable Implementation
What you'll learn: How to create threads using anonymous classes that implement Runnable for simple, one-time tasks.
The Problem: One-Off Thread Tasks
When you need to execute code on a separate thread just once—without creating a full, named class—anonymous classes provide a clean, inline solution. Since Runnable is a simple interface with a single run() method, it's a perfect candidate for anonymous class implementation.
Anonymous Runnable Syntax
Instead of creating a separate class that implements Runnable, you can define the implementation right where you create the thread:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Running in separate thread!");
// Your task code here
}
});
thread.start();
This creates an anonymous class that implements Runnable inline, overriding the run() method with your specific task.
Accessing Enclosing Scope
Anonymous Runnable implementations can capture effectively final variables from the enclosing scope:
String message = "Hello from main thread";
int count = 5;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < count; i++) {
System.out.println(message + " - iteration " + i);
}
}
});
thread.start();
The anonymous class captures message and count from the outer method scope.
Why This Matters
This pattern is extremely common for quick background tasks, UI event handling in frameworks, and any scenario where defining a full class would be overkill. You get clean, localized code without polluting your namespace with single-use class definitions.
Key Takeaway: Use anonymous classes implementing Runnable when creating threads for one-off tasks—it keeps the task logic close to where the thread is created, improving code readability without requiring separate class definitions.