Java Runnable Interface

Su Suriya Ravichandran Updated 18 Nov 2026
13 min read ·Lesson 184 of 306

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();
}
PartMeaning
void run()The single method: the code of the task
No parametersInput must come from fields or captured variables
Returns voidThe task cannot return a value directly
No throws clauserun() cannot throw checked exceptions such as IOException
@FunctionalInterfaceIt 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:

  • GreetingTask implements Runnable by providing a run() 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 calls run().

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:

  • () -> ... matches run(): no parameters, no return value.
  • LambdaRunnableDemo::backupDatabase points to a static method with no parameters, so it fits Runnable too.
  • app::processFiles points to an instance method of the object app. When the thread runs it, it calls app.processFiles().
  • The threads have no names, so they get the default names Thread-0, Thread-1 and Thread-2.

Note: A method reference works as a Runnable when 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 same ticketsLeft and sold fields.
  • getAndUpdate reads 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 int and ticketsLeft--, 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-1 sold almost everything because it started first. The scheduler decides.

Note: If each thread should have its own state, create a separate Runnable object 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 Runnableextends Thread
Your class can extend another classYesNo, it already extends Thread
Separates the task from the threadYesNo, the task is the thread
Works with thread pools (ExecutorService)YesNot in a useful way
One task object shared by many threadsYesNo
Can be a lambdaYesNo

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:

  • SalesReport inherits status handling from Report and, at the same time, implements Runnable. With extends 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 IOException on run().
  • 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.readString declares throws IOException. Inside a Runnable lambda, the compiler forces you to catch it, because run() 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>:

RunnableCallable<V>
Methodvoid run()V call() throws Exception
Returns a valueNoYes, of type V
Can throw checked exceptionsNoYes
Works with new Thread(...)YesNo, needs an ExecutorService
Available sinceJava 1.0Java 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, named pool-1-thread-1 and pool-1-thread-2.
  • execute(task) hands the task to the pool and returns immediately.
  • submit(task) also returns a Future. get() waits until the task has finished; for a Runnable, the result is always null.
  • Since Java 19, ExecutorService is AutoCloseable. Leaving the try block 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:

  • timed returns a new Runnable that records the time, calls the original task's run(), and prints the duration.
  • inSequence returns one Runnable that 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:

  1. Jobs as data. Each Job record pairs a name with a Runnable. Adding a new job means adding one line to the list. The work calls stand in for real work such as deleting files.
  2. A wrapping Runnable. safely(job) returns a new Runnable that runs the job, measures it, and catches any RuntimeException. The jobs themselves contain no error handling or timing code.
  3. 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.
  4. Thread-safe results. All jobs write their outcome into one ConcurrentHashMap, a map designed to be updated by several threads at once. A plain HashMap could lose entries.
  5. Failure isolation. The usage report job throws, but the wrapper records FAILED with the message and the other four jobs finish normally.
  6. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Runnable Interface and get answers drawn from it.

Signed-in readers only.