Runnable & Thread
Implementing Runnable
A class implementing Runnable, run on a Thread
class PrinterTask implements Runnable {
private final String label;
PrinterTask(String label) {
this.label = label;
}
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(label + " - step " + i);
}
}
}
public class RunnableDemo {
public static void main(String[] args) {
Runnable task = new PrinterTask("worker");
Thread thread = new Thread(task); // hand the Runnable to a Thread
thread.start();
}
}worker - step 1 worker - step 2 worker - step 3
Why This Is the Preferred Pattern
Lambdas as a Concise Runnable
Since Runnable is a functional interface — exactly one abstract method — a lambda expression can stand in for an entire class definition. This is by far the most common way Runnable shows up in modern Java code.
Before: an explicit Runnable implementation
Runnable verbose = new Runnable() {
@Override
public void run() {
System.out.println("Running in a background thread");
}
};
new Thread(verbose).start();After: the same thing as a lambda
Runnable concise = () -> System.out.println("Running in a background thread");
new Thread(concise).start();
// or, skipping the variable entirely:
new Thread(() -> System.out.println("Running in a background thread")).start();Running in a background thread Running in a background thread
Approach | Extends/implements | Reusable across execution strategies |
|---|---|---|
extends Thread | Extends a concrete class — uses up Java's single-inheritance slot | No — tied to being a Thread |
implements Runnable | Implements an interface — class stays free to extend something else | Yes — the same Runnable works with plain Thread or a thread pool |
Implementing Runnable and passing it to new Thread(runnable) is the preferred pattern over extending Thread
Runnable separates "what work to do" from "how it gets executed"
Runnable is a functional interface, so lambdas can replace a full class or anonymous class
A Runnable built this way is portable to other execution strategies like thread pools