The Runnable Interface: The Project Manager

The Runnable Interface: The Project Manager in Java: Picture an orchestra a few minutes before a concert. The conductor has a stack of scores on the stand.

The Analogy:

Picture an orchestra a few minutes before a concert. The conductor has a stack of scores on the stand. Each score is a dense set of instructions -- this many bars, this loud, this fast, this instrument -- but the score itself makes no sound. It just sits there describing what ought to happen. The sound comes from a player who picks the part up and works through it, bar by bar. The score is the what; the player is the who, and they are two entirely separate things.

A Runnable is the score. It is an object whose whole job is to hold one method, run(), that describes a piece of work to be done. It does not run itself, any more than a sheet of music plays itself. A Thread is the player: a real worker that the operating system can schedule onto a CPU. You hand the score to a player -- new Thread(myRunnable) -- and then tell that player to begin -- start(). The thread then calls run() for you, on its own.

Keeping the score and the player apart is the entire point. Because they are separate, one score can be handed to several players at once: the same Runnable passed to three different Thread objects. And a player who simply reads whatever score is placed in front of them stays free to be other things too -- a teacher, a soloist, a section leader -- because reading a score is a skill they add, not an identity they become. That is exactly why you implements Runnable rather than extends Thread: a Java class gets only one parent, and if you spend that one slot becoming a Thread, the class can never extend anything else again.

The classic failure is the impatient conductor who, instead of handing the score to a player, reads it aloud and taps out the rhythm on the podium themselves. Every note is correct -- but nothing has been delegated. The conductor is doing the playing, alone, while the orchestra sits idle. In code this is calling run() directly instead of start(). It compiles, it runs, it prints exactly what you expected, and it never creates a new thread at all: the work happens on the calling thread, in order, with no concurrency. Nothing warns you, because calling a public method is perfectly legal. It is the single most common threading mistake a beginner makes.

Syntax or Core Structure

public class Concert {
    // A Runnable is a "score": it only describes the work, it does not run itself.
    static class PlayScore implements Runnable {
        private final String part;
        PlayScore(String part) { this.part = part; }
        public void run() {
            System.out.println(part + " plays its line");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable violin = new PlayScore("Violin");
        Runnable flute  = () -> System.out.println("Flute plays its line"); // a lambda IS a Runnable

        Thread p1 = new Thread(violin); // hand the score to a player
        Thread p2 = new Thread(flute);

        p1.start();   // tell the first player to begin
        p1.join();    // wait until the violin has finished
        p2.start();
        p2.join();    // wait until the flute has finished

        System.out.println("Movement complete");
    }
}

Output:

Violin plays its line
Flute plays its line
Movement complete

The order is guaranteed here only because each join() forces one player to finish before the next line runs. Drop the join() calls and the two lines could print in either order, or interleaved -- the scheduler, not your source, would decide.

Technical Depth:

Why Implement Runnable Rather Than Extend Thread

The older tutorials often show class MyThread extends Thread, and it works, but it quietly spends your one and only inheritance slot on Thread. Runnable is an interface, so a class can implement it and still extend a domain class -- class ReportJob extends Document implements Runnable. It also separates the task from the machinery that runs it, which is what lets the same task drop straight into a thread pool later.

Aspectimplements Runnableextends Thread
Inheritance slotLeft free; the class can still extend another classUsed up; the class can extend nothing else
What you writeA task object, handed to a ThreadA Thread subclass that is the task
ReuseOne Runnable can feed many threads or a poolThe subclass instance is one thread, single use
Fits executorsYes -- ExecutorService accepts RunnableNot directly; you wrap or rework it
RecommendedYes, in almost all codeRarely; only to change Thread behaviour itself

start() Versus run(), And What join() Guarantees

These three calls trip up nearly everyone at first. start() asks the JVM to create a fresh operating-system thread and have that thread call your run() -- it returns to you immediately, before the task has done anything. Calling run() yourself does no such thing: it simply executes the method on the current thread, like any ordinary call, with no concurrency at all. join() is the counterpart to start(): the calling thread parks itself until the target thread has finished, which is how you know a result is ready to read. join() is declared to throw InterruptedException, so it must sit in a try or be declared with throws.

CallRuns onNew thread?Blocks caller?Typical use
start()The new threadYesNo -- returns at onceLaunch the task concurrently
run() called directlyThe calling threadNoYes -- runs inline to the endAlmost always a bug
join()(nothing; it waits)NoYes -- until the target endsWait before reading a result

A second rule the table hides: you may call start() on a given Thread object only once. A thread that has finished cannot be restarted; calling start() again throws IllegalThreadStateException. If you need to run the same task twice, hand the same Runnable to two Thread objects, or use a pool.

Here is the difference made concrete. Thread.currentThread().getName() reports which thread is actually executing a line:

Runnable task = () -> System.out.println("run by " + Thread.currentThread().getName());

task.run();                          // direct call: runs now, on THIS thread
new Thread(task, "worker").start();  // start(): a brand-new thread runs it

Output:

run by main
run by worker

The order is certain even without a join(): task.run() is an ordinary synchronous call, so "run by main" is printed and finished before start() is even reached. The direct call never left the main thread; only start() produced a second worker. That one line of output is the whole bug in miniature -- swap start() for run() and every task quietly collapses back onto the caller.

Real World Example:

public class ReportBatch {
    // The task carries its own data and writes only its own slot -- no shared write target.
    static class RenderTask implements Runnable {
        private final int id;
        private final int[] results;
        RenderTask(int id, int[] results) { this.id = id; this.results = results; }
        public void run() {
            int checksum = 0;
            for (int line = 1; line <= id; line++) checksum += line; // stand-in for "render" work
            results[id - 1] = checksum;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int n = 5;
        int[] results = new int[n];
        Thread[] workers = new Thread[n];

        for (int id = 1; id <= n; id++) {
            workers[id - 1] = new Thread(new RenderTask(id, results), "render-" + id);
        }
        for (Thread w : workers) w.start(); // every player begins
        for (Thread w : workers) w.join();  // wait for every one to finish

        // Only after every join is it safe to read the shared array.
        for (int id = 1; id <= n; id++) {
            System.out.println("report-" + id + " checksum " + results[id - 1]);
        }
        System.out.println("batch complete");
    }
}

Output:

report-1 checksum 1
report-2 checksum 3
report-3 checksum 6
report-4 checksum 10
report-5 checksum 15
batch complete

This program renders five reports at once. Each report is a RenderTask -- a Runnable that knows its own id, does a little work (here, a checksum standing in for real rendering), and stores the answer in its own slot of a shared array. main builds five tasks, wraps each in a named Thread, starts them all, and only then loops over the workers calling join(). The tasks run in whatever order the scheduler picks, but the final printout is always identical because the print loop walks the ids in order, not in finish order.

The reason Runnable earns its keep here is that the task is a plain object carrying its own data. That means the leap to an ExecutorService -- a managed pool of reusable threads -- is almost nothing: pool.submit(new RenderTask(id, results)) instead of new Thread(...).start(). Had RenderTask instead extends Thread, it would be welded to the raw-thread approach and you would rewrite it to move to a pool. Separating the what from the who is what keeps that door open.

The safety of reading results rests entirely on the join() loop. join() does more than make main wait -- it establishes a happens-before relationship, the JVM's guarantee that everything a thread wrote before it ended is visible to whoever joins it. Read the array before the joins complete and you would not just get partial data; you could get stale values the reading thread never saw updated, because without that guarantee there is no promise the writes are visible across threads at all.

The honest limits: this code spins up one raw thread per task, which is fine for five reports and a poor idea for fifty thousand -- threads are not free, and a real batch of that size wants a bounded pool. There is also a genuine design flaw in the shared int[] results. It is safe only because the invariant "each task writes a different index" holds; nothing in the code enforces that. One copy-paste bug that passes the wrong id, and two tasks write the same slot with no synchronization and no error -- a silent data race that a ConcurrentHashMap keyed by id, or a per-task return value collected through a Future, would have made structurally impossible.

Common Mistakes

  1. Calling run() instead of start(). worker.run() executes the task on the current thread, in order, with no new thread created. It compiles and prints the right thing, which is exactly why the bug survives. Only start() launches a concurrent thread.
  1. Calling start() twice on the same Thread. A thread runs once. Once it has finished, start() throws IllegalThreadStateException. To repeat the work, wrap the same Runnable in a new Thread, or submit it to a pool again.
  1. Reading a shared result before join(). If main reads the results array before the workers have joined, it may see half-written data or values that were never made visible across threads. The join() is what makes the writes both complete and visible.
  1. Expecting a fixed print order without join(). Two started threads print in whatever order the scheduler chooses, and it can differ run to run. If order matters, enforce it with join() or with proper coordination -- never assume it.
  1. Sharing mutable state between tasks with no synchronization. The moment two threads write the same variable, field, or collection without a lock or a concurrent type, you have a data race. It may look fine in testing and corrupt data in production under load.
  1. Trying to throw a checked exception out of run(). Runnable.run() declares no checked exceptions, so you cannot let one escape it. You must catch it inside run(), or use Callable (which returns a value and may throw) with an executor instead.
  1. Extending Thread out of habit. extends Thread spends the class's one inheritance slot and welds the task to raw threads. Unless you are genuinely subclassing Thread to change its behaviour, implement Runnable.
  1. Forgetting InterruptedException. Both join() and Thread.sleep() are declared to throw it. The code will not compile until you handle it with a try/catch or declare throws -- and swallowing it silently is its own mistake (see Best Practices).
  1. Assuming a fresh Runnable per thread means the threads are isolated. If three RenderTask objects all hold a reference to the same array or counter, they are sharing state regardless of being separate objects. Isolation comes from what the task touches, not from how many task objects you made.

Best Practices

  • Prefer Runnable (or Callable) over extends Thread. It keeps the inheritance slot free, separates the task from the worker, and lets the same task run on a raw thread today and a pool tomorrow with no rewrite.
  • Use an ExecutorService for anything beyond a demo. Creating threads by hand does not scale and offers no queueing, no bounds, and no reuse. A pool from Executors gives you all three, and submit hands back a Future for the result.
  • Always join() -- or collect Futures -- before reading results. Never read what a worker produced until you have proof it finished. That proof (a completed join() or Future.get()) is also what makes the worker's writes visible to you.
  • Give each task its own output target. A task that writes only its own slot, or returns its own value, cannot race another. Reach for shared mutable state only when you must, and then guard it with a lock or a concurrent type.
  • Name your threads. new Thread(task, "render-3") costs one argument and turns an unreadable stack trace or thread dump into something you can actually debug.
  • Keep run() bodies short and self-contained. A task that carries its own data and does one clear job is easy to reason about, test, and later drop into a pool. Long run() methods that reach out to shared globals are where races hide.
  • Use a lambda only for a trivial task. () -> doThing() is perfect for one line. Once the task needs its own fields and constructor, a named class reads better and is easier to test in isolation.
  • Handle InterruptedException deliberately. At minimum, restore the flag with Thread.currentThread().interrupt() before returning. Swallowing it with an empty catch hides a cancellation request and is a classic source of unresponsive threads.

Practice Exercises

  1. The Lambda Thread: Modern Java lets a Runnable be a lambda -- new Thread(() -> System.out.println("Hi")).start();. Write a thread whose task counts down from 5 to 1, one number per line, using the lambda shortcut. Then join() it from main and print "liftoff" afterwards so the order is guaranteed.
  1. The Interface Mix: Create a class Worker that extends Person (give Person a name field) and implements Runnable, so its run() prints "<name> is working". This is the case extends Thread cannot handle -- prove to yourself it compiles and runs.
  1. Multiple Workers: Create one Runnable object and pass it to three different Thread objects, starting all three. Observe that the single task runs three times, once per thread. Then add a shared int counter the task increments and explain, in a comment, why the final value may be less than 3.