Anonymous Classes for One-Off Threads
You'll learn how to create quick, disposable threads without cluttering your codebase with named classes.
When you need a thread for a simple, one-time task—like printing a message or performing a quick calculation—creating a separate class file or even a named inner class feels like overkill. Anonymous classes let you define and instantiate a Runnable implementation right at the point where you need it, perfect for throwaway threads.
The Core Idea
An anonymous class is a class without a name, defined inline where you use it. Instead of creating a separate Runnable implementation, you declare it on-the-fly as you pass it to the Thread constructor:
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Quick task running!");
}
});
t.start();
Here, new Runnable() { ... } creates an anonymous class implementing Runnable. You define the run method right there, and the instance is immediately passed to Thread. No separate class file, no reusable component—just a single-use implementation.
When to Use This Pattern
Anonymous classes shine when:
- The task is simple and won't be reused elsewhere
- You want to keep related code together visually
- You're prototyping or writing quick utility threads
Think of it like ordering a custom coffee: you don't need a named recipe on the menu if you're only getting it once—just tell the barista exactly what you want, right then.
Contrast with Lambda
While lambda expressions (already covered in your phase) are now preferred for single-method interfaces like Runnable, anonymous classes remain useful when you need multiple methods or fields within the implementation, or when working with older codebases.
Key Takeaway: Anonymous classes let you create Runnable implementations inline for quick, non-reusable threads, keeping your code concise when a full class definition is unnecessary.