Java Runnable Interface
The Java Runnable interface (java.lang.Runnable) represents a task: a piece of code that can be run, usually on another thread. It separates what should be done (the task) from who does it (a Thread, a thread pool, or the current thread).
Runnable is the most common way to give work to threads in Java. This lesson shows how to implement it, how to write it as a lambda or method reference, how one task can be shared by several threads, and how to run tasks in a thread pool.
What Is the Java Runnable Interface?
Runnable is one of the smallest interfaces in Java. Here is its full definition from the JDK:
@FunctionalInterface
public interface Runnable {
void run();
}
| Part | Meaning |
|---|---|
void run() | The single method: the code of the task |
| No parameters | Input must come from fields or captured variables |
Returns void | The task cannot return a value directly |
No throws clause | run() cannot throw checked exceptions such as IOException |
@FunctionalInterface | It has one abstract method, so a lambda can implement it |
A Runnable is not a thread. It is an ordinary object with a run() method. It becomes concurrent only when you hand it to something that runs it on another thread.
public class BasicRunnableDemo {
public static void main(String[] args) throws InterruptedException {
Runnable greeting = new GreetingTask("Asha");
greeting.run(); // a Runnable is just an object with a run() method
Thread thread = new Thread(greeting, "greeter");
thread.start(); // the same task, now on a new thread
thread.join();
}
}
class GreetingTask implements Runnable {
private final String name;
GreetingTask(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("Hello, " + name + "! (from " + Thread.currentThread().getName() + ")");
}
}
Output:
Hello, Asha! (from main)
Hello, Asha! (from greeter)
How it works:
GreetingTaskimplementsRunnableby providing arun()method. The task's input, the name, comes through the constructor.- Calling
greeting.run()directly runs the task on the current thread,main, like any method call. new Thread(greeting, "greeter")wraps the same task in a thread.start()creates the new thread, and that thread callsrun().
Writing a Runnable as a Lambda or Method Reference
Because Runnable is a functional interface, you rarely need a separate class for short tasks. A lambda with no parameters, or a method reference to a method that takes no arguments, can stand in for a Runnable.
public class LambdaRunnableDemo {
static void backupDatabase() {
System.out.println("Backing up database on " + Thread.currentThread().getName());
}
private int processedFiles = 0;
void processFiles() {
processedFiles = 3;
System.out.println("Processed " + processedFiles + " files on " + Thread.currentThread().getName());
}
public static void main(String[] args) throws InterruptedException {
// 1. Lambda expression
Runnable sayHello = () -> System.out.println("Hello from " + Thread.currentThread().getName());
// 2. Method reference to a static method
Runnable backup = LambdaRunnableDemo::backupDatabase;
// 3. Method reference to an instance method of a specific object
LambdaRunnableDemo app = new LambdaRunnableDemo();
Runnable process = app::processFiles;
for (Runnable task : new Runnable[] {sayHello, backup, process}) {
Thread t = new Thread(task);
t.start();
t.join();
}
}
}
Output:
Hello from Thread-0
Backing up database on Thread-1
Processed 3 files on Thread-2
How it works:
() -> ...matchesrun(): no parameters, no return value.LambdaRunnableDemo::backupDatabasepoints to a static method with no parameters, so it fitsRunnabletoo.app::processFilespoints to an instance method of the objectapp. When the thread runs it, it callsapp.processFiles().- The threads have no names, so they get the default names
Thread-0,Thread-1andThread-2.
Note: A method reference works as a
Runnablewhen the method takes no arguments. If the method returns a value, Java simply ignores it.
Sharing One Runnable Between Multiple Threads
Several threads can run the same Runnable object. They then share its fields, which is useful for a shared job such as selling from one stock of tickets. It also means the fields must be safe to change from several threads at once.
import java.util.concurrent.atomic.AtomicInteger;
public class SharedRunnableDemo {
// ONE ticket counter object shared by several threads
static class TicketSeller implements Runnable {
private final AtomicInteger ticketsLeft = new AtomicInteger(10);
private final AtomicInteger sold = new AtomicInteger();
@Override
public void run() {
while (true) {
// Atomically take one ticket: no two threads can get the same number
int ticket = ticketsLeft.getAndUpdate(left -> left > 0 ? left - 1 : 0);
if (ticket == 0) {
return; // sold out
}
sold.incrementAndGet();
System.out.println(Thread.currentThread().getName() + " sold ticket #" + ticket);
}
}
}
public static void main(String[] args) throws InterruptedException {
TicketSeller seller = new TicketSeller(); // a single Runnable instance
Thread counter1 = new Thread(seller, "counter-1");
Thread counter2 = new Thread(seller, "counter-2");
Thread counter3 = new Thread(seller, "counter-3");
counter1.start();
counter2.start();
counter3.start();
counter1.join();
counter2.join();
counter3.join();
System.out.println("Total sold: " + seller.sold.get() + ", left: " + seller.ticketsLeft.get());
}
}
Output from one run (which counter sells which ticket changes every run):
counter-1 sold ticket #10
counter-1 sold ticket #8
counter-1 sold ticket #7
counter-1 sold ticket #6
counter-1 sold ticket #5
counter-1 sold ticket #4
counter-1 sold ticket #3
counter-1 sold ticket #2
counter-1 sold ticket #1
counter-2 sold ticket #9
Total sold: 10, left: 0
How it works:
- All three threads run
seller.run(), so they all work on the sameticketsLeftandsoldfields. getAndUpdatereads the current count and stores the new one in a single, indivisible step. Two threads can never take the same ticket, and the count never goes below zero.- With a plain
intandticketsLeft--, two threads could read the same value at the same time and sell the same ticket twice, the race condition described in Java Threads: Thread Basics. - The work is not split evenly: in this run,
counter-1sold almost everything because it started first. The scheduler decides.
Note: If each thread should have its own state, create a separate
Runnableobject per thread instead of sharing one.
Runnable vs Extending Thread
Both approaches put your code in a run() method. The difference is the design.
implements Runnable | extends Thread | |
|---|---|---|
| Your class can extend another class | Yes | No, it already extends Thread |
| Separates the task from the thread | Yes | No, the task is the thread |
Works with thread pools (ExecutorService) | Yes | Not in a useful way |
| One task object shared by many threads | Yes | No |
| Can be a lambda | Yes | No |
The first row matters most in real applications, where classes often already belong to a hierarchy.
public class ExtendAndRunDemo {
public static void main(String[] args) throws InterruptedException {
SalesReport report = new SalesReport("November");
Thread t = new Thread(report, "report-thread");
t.start();
t.join();
System.out.println("Report status: " + report.getStatus());
}
}
// An existing base class used by all reports in the application
class Report {
private String status = "PENDING";
protected void setStatus(String status) { this.status = status; }
public String getStatus() { return status; }
}
// Can extend Report AND be run on a thread, because Runnable is an interface
class SalesReport extends Report implements Runnable {
private final String month;
SalesReport(String month) {
this.month = month;
}
@Override
public void run() {
setStatus("RUNNING");
System.out.println("Building " + month + " sales report on " + Thread.currentThread().getName());
setStatus("DONE");
}
}
Output:
Building November sales report on report-thread
Report status: DONE
How it works:
SalesReportinherits status handling fromReportand, at the same time, implementsRunnable. Withextends Thread, this would be impossible, because a Java class has only one superclass.- After
join(), main reads the status that the report thread set.join()guarantees the update is visible.
Runnable Limitations: No Return Value and No Checked Exceptions
run() returns void and declares no exceptions. Two practical consequences follow:
- Checked exceptions must be handled inside the task. You cannot write
throws IOExceptiononrun(). - Results must be stored somewhere, for example in a field, as shown in Create a Thread in Java.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class CheckedExceptionDemo {
public static void main(String[] args) throws InterruptedException {
// run() cannot declare "throws IOException", so the task must handle it itself
Runnable readConfig = () -> {
try {
String content = Files.readString(Path.of("missing-config.txt"));
System.out.println("Config: " + content);
} catch (IOException e) {
System.out.println("Could not read config: " + e.getClass().getSimpleName()
+ " - using defaults");
}
};
Thread loader = new Thread(readConfig, "config-loader");
loader.start();
loader.join();
}
}
Output (when missing-config.txt does not exist):
Could not read config: NoSuchFileException - using defaults
How it works:
Files.readStringdeclaresthrows IOException. Inside aRunnablelambda, the compiler forces you to catch it, becauserun()does not allow it to escape.- The task decides on a fallback (default settings) instead of failing.
When a task needs to return a value or throw a checked exception, Java offers Callable<V>:
Runnable | Callable<V> | |
|---|---|---|
| Method | void run() | V call() throws Exception |
| Returns a value | No | Yes, of type V |
| Can throw checked exceptions | No | Yes |
Works with new Thread(...) | Yes | No, needs an ExecutorService |
| Available since | Java 1.0 | Java 5 |
The Callable Interface and Future Interface lessons later in this section cover Callable in detail.
Running Runnable Tasks with ExecutorService
Creating a new Thread for every task works, but real applications usually hand tasks to a thread pool: a small set of threads that are reused for many tasks. An ExecutorService accepts Runnable tasks directly.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ExecutorRunnableDemo {
public static void main(String[] args) throws Exception {
Runnable resizeImage = () -> System.out.println("Resizing image on " + Thread.currentThread().getName());
// A pool of 2 reusable threads; try-with-resources waits for all tasks, then shuts it down
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
pool.execute(resizeImage); // fire and forget
Future<?> result = pool.submit(resizeImage); // returns a Future
System.out.println("submit() result: " + result.get()); // a Runnable has no value: null
}
System.out.println("Pool closed");
}
}
Output (the first two lines can show the pool threads in another order):
Resizing image on pool-1-thread-1
Resizing image on pool-1-thread-2
submit() result: null
Pool closed
How it works:
Executors.newFixedThreadPool(2)creates a pool with two threads, namedpool-1-thread-1andpool-1-thread-2.execute(task)hands the task to the pool and returns immediately.submit(task)also returns aFuture.get()waits until the task has finished; for aRunnable, the result is alwaysnull.- Since Java 19,
ExecutorServiceisAutoCloseable. Leaving thetryblock waits for all submitted tasks and shuts the pool down.
Combining and Wrapping Runnable Tasks
Since a Runnable is an object, you can pass it to methods and return new Runnables that wrap it. This lets you add behaviour such as timing or logging without changing the original task.
public class ComposeDemo {
// Wraps any Runnable with timing and logging - the original task does not change
static Runnable timed(String label, Runnable task) {
return () -> {
long start = System.nanoTime();
task.run();
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println(" [" + label + "] took about " + Math.round(ms / 10.0) * 10 + " ms");
};
}
// Combines several Runnables into one that runs them in order
static Runnable inSequence(Runnable... steps) {
return () -> {
for (Runnable step : steps) {
step.run();
}
};
}
static void pause(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Runnable download = () -> { System.out.println("Downloading..."); pause(200); };
Runnable unzip = () -> { System.out.println("Unzipping..."); pause(100); };
Runnable install = () -> { System.out.println("Installing..."); pause(150); };
Runnable pipeline = inSequence(
timed("download", download),
timed("unzip", unzip),
timed("install", install));
Thread installer = new Thread(timed("whole pipeline", pipeline), "installer");
installer.start();
installer.join();
}
}
Output (times can differ by a few milliseconds):
Downloading...
[download] took about 200 ms
Unzipping...
[unzip] took about 100 ms
Installing...
[install] took about 150 ms
[whole pipeline] took about 460 ms
How it works:
timedreturns a newRunnablethat records the time, calls the original task'srun(), and prints the duration.inSequencereturns oneRunnablethat runs several others in order, on the same thread.- The pipeline is itself wrapped in
timed, so the whole thing is measured too. The total is slightly more than 450 ms because of the extra printing and the time to wake up from each sleep.
Real-World Example: Running Nightly Maintenance Jobs
A web application runs several maintenance jobs every night: clearing temporary files, rotating logs, rebuilding the search index and so on. The jobs are independent, so they can run at the same time. One failing job must not stop the others, and the operator wants a short report at the end.
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class MaintenanceJobs {
record Job(String name, Runnable action) { }
static final Map<String, String> RESULTS = new ConcurrentHashMap<>();
// Decorator: catches failures and records the outcome of each job
static Runnable safely(Job job) {
return () -> {
long start = System.currentTimeMillis();
try {
job.action().run();
RESULTS.put(job.name(), "OK " + Math.round((System.currentTimeMillis() - start) / 10.0) * 10 + " ms");
} catch (RuntimeException e) {
RESULTS.put(job.name(), "FAILED " + e.getMessage());
}
};
}
static void work(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
List<Job> jobs = List.of(
new Job("clear-temp-files", () -> work(300)),
new Job("rotate-logs", () -> work(200)),
new Job("rebuild-search-index", () -> work(500)),
new Job("send-usage-report", () -> {
work(100);
throw new IllegalStateException("mail server unreachable");
}),
new Job("expire-sessions", () -> work(150)));
long start = System.currentTimeMillis();
Thread[] threads = new Thread[jobs.size()];
for (int i = 0; i < jobs.size(); i++) {
Job job = jobs.get(i);
threads[i] = Thread.ofVirtual().name(job.name()).start(safely(job));
}
for (Thread t : threads) {
t.join();
}
long total = System.currentTimeMillis() - start;
for (Job job : jobs) {
System.out.printf("%-22s %s%n", job.name(), RESULTS.get(job.name()));
}
long failed = RESULTS.values().stream().filter(r -> r.startsWith("FAILED")).count();
System.out.println(jobs.size() + " jobs, " + failed + " failed, finished in about "
+ Math.round(total / 100.0) * 100 + " ms");
}
}
Output:
clear-temp-files OK 300 ms
rotate-logs OK 200 ms
rebuild-search-index OK 500 ms
send-usage-report FAILED mail server unreachable
expire-sessions OK 150 ms
5 jobs, 1 failed, finished in about 500 ms
How it works:
- Jobs as data. Each
Jobrecord pairs a name with aRunnable. Adding a new job means adding one line to the list. Theworkcalls stand in for real work such as deleting files. - A wrapping
Runnable.safely(job)returns a newRunnablethat runs the job, measures it, and catches anyRuntimeException. The jobs themselves contain no error handling or timing code. - One virtual thread per job.
Thread.ofVirtual().name(job.name()).start(...)starts each wrapped job on its own named virtual thread. Virtual threads are cheap, which suits short background jobs that mostly wait. - Thread-safe results. All jobs write their outcome into one
ConcurrentHashMap, a map designed to be updated by several threads at once. A plainHashMapcould lose entries. - Failure isolation. The usage report job throws, but the wrapper records
FAILEDwith the message and the other four jobs finish normally. - Overall time. The jobs add up to 1250 ms of work, but because they overlap, the whole run takes about as long as the slowest job, 500 ms.
The next lesson, Java Thread States, shows what happens inside each of these threads as it moves from NEW to RUNNABLE, waits, and finally reaches TERMINATED.