Skip to lesson

Thread vs Runnable vs Callable

An interviewer opens concurrency with "how do you create a thread?" and follows up with "why start() and not run()?". They are checking that you separate the task from the thread, know the six states, and know where results and exceptions go.

Three ways to create a thread: Thread, Runnable, Callable

Thread is a separate path of execution inside a program. It has its own call stack but shares the heap with the other threads of the same program.

Every thread answer starts with the three ways to create work. This program makes one task each way: extend Thread, pass a Runnable lambda, and submit a Callable to an executor.

Example 1 · All three ways in one program

CreateThreadsDemo.javaJava
import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
class MarksThread extends Thread {               // way 1: extend Thread    int total;
    MarksThread() {        super("marks-thread");    }
    @Override    public void run() {        for (int m : new int[] {78, 64, 91}) {            total += m;        }    }}
public class CreateThreadsDemo {    public static void main(String[] args) throws Exception {        MarksThread t1 = new MarksThread();        t1.start();
        int[] feeTotal = new int[1];        Runnable feeTask = () -> feeTotal[0] = 45000 + 12000;   // way 2: Runnable        Thread t2 = new Thread(feeTask, "fee-thread");        t2.start();
        Callable<String> otpTask = () -> "OTP-" + (100000 + 4821); // way 3: Callable        ExecutorService pool = Executors.newSingleThreadExecutor();        Future<String> otp = pool.submit(otpTask);
        t1.join();        t2.join();        System.out.println(t1.getName() + " total: " + t1.total);        System.out.println(t2.getName() + " total: " + feeTotal[0]);        System.out.println("Callable result: " + otp.get());        pool.shutdown();    }}
Output
marks-thread total: 233
fee-thread total: 57000
Callable result: OTP-104821

What this code does

  • MarksThread extends Thread; the fee task is a Runnable lambda passed to new Thread; the OTP task is a Callable submitted to an executor, which returns a Future.
  • join() waits for both threads before main reads their results, and otp.get() waits for the Callable. Without join the totals could still be 0 when printed.

Model answer, spoken: "I prefer Runnable or Callable over extending Thread. Java has single inheritance, so extending Thread uses up the one parent. A Runnable separates the task from the thread, and the same task can go to a thread pool. In real code I submit tasks to an ExecutorService."

The three task types differ in what they allow:

  • Runnable.run(): no return value, cannot throw checked exceptions.
  • Callable.call(): returns a value, may throw checked exceptions.
  • Thread itself implements Runnable; name your threads so thread dumps are readable.

start() vs run()

join() is a Thread method that makes the calling thread wait until the other thread has finished. It is how main safely reads a result that another thread computed.

start() and run() look alike but behave very differently. This program runs the same task both ways and prints which thread did the work.

Example 2 · Predict the output: run() vs start()

StartVsRunDemo.javaJava
public class StartVsRunDemo {    public static void main(String[] args) throws InterruptedException {        String[] ranOn = new String[2];
        Thread t = new Thread(() -> ranOn[0] = Thread.currentThread().getName(), "worker");        t.run();                                   // a normal method call        System.out.println("run()   executed on: " + ranOn[0]);
        Thread u = new Thread(() -> ranOn[1] = Thread.currentThread().getName(), "worker");        u.start();                                 // a new thread calls run()        u.join();        System.out.println("start() executed on: " + ranOn[1]);
        try {            u.start();                             // a thread can be started only once        } catch (IllegalThreadStateException e) {            System.out.println("Second start(): IllegalThreadStateException");        }    }}
Output
run()   executed on: main
start() executed on: worker
Second start(): IllegalThreadStateException

What this code does

  • t.run() ran on main, the current thread, because it is an ordinary method call. u.start() created a new thread named worker, which called run().
  • Starting u a second time throws IllegalThreadStateException, even though it already finished.

start() asks the JVM to create a new thread, which then calls run(). Calling run() yourself is an ordinary method call on the current thread, so nothing runs in parallel. A thread can be started only once: a second start() throws IllegalThreadStateException, even after the thread has finished.

Spoken: "start() creates a new thread of execution; run() just runs the code on the thread that called it. That is why we always call start()."

Predict the output

Predict the thread output

Read the code, then pick what it prints.

Round 1 of 3

run() is called directly, not start().

public class Demo {
public static void main(String[] args) {
Thread t = new Thread(() -> System.out.print(Thread.currentThread().getName() + " "));
t.run();
System.out.println("done");
}
}

Thread states; sleep vs wait; join

sleep(ms) is a static Thread method that pauses the current thread and keeps its locks. wait() is an Object method, needs synchronized on that object, and releases the lock while waiting.

A thread moves through six states. This program drives one thread into each state and prints it, polling until the state appears, so the output is the same on every run.

Thread life cycle. NEW goes to RUNNABLE when start() is called. A RUNNABLE thread can move to BLOCKED (waiting for a lock), WAITING (wait or join) or TIMED_WAITING (sleep with a time) and back to RUNNABLE. When run() ends the thread becomes TERMINATED.

Example 3 · Seeing NEW, TIMED_WAITING, WAITING, BLOCKED and TERMINATED

ThreadStatesDemo.javaJava
public class ThreadStatesDemo {    static final Object lock = new Object();
    static void waitFor(Thread t, Thread.State expected) throws InterruptedException {        while (t.getState() != expected) {            Thread.sleep(5);        }        System.out.println(t.getName() + ": " + t.getState());    }
    public static void main(String[] args) throws InterruptedException {        Thread sleeper = new Thread(() -> {            try {                Thread.sleep(500);            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        }, "sleeper");        System.out.println(sleeper.getName() + ": " + sleeper.getState());        sleeper.start();        waitFor(sleeper, Thread.State.TIMED_WAITING);
        Thread watcher = new Thread(() -> {            synchronized (lock) {                try {                    lock.wait();                     // releases the lock and waits                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                }            }        }, "watcher");        watcher.start();        waitFor(watcher, Thread.State.WAITING);
        Thread blocked = new Thread(() -> {            synchronized (lock) {                lock.notifyAll();            }        }, "blocked");        synchronized (lock) {                        // main holds the lock            blocked.start();            waitFor(blocked, Thread.State.BLOCKED);        }
        sleeper.join();        watcher.join();        blocked.join();        waitFor(sleeper, Thread.State.TERMINATED);    }}
Output
sleeper: NEW
sleeper: TIMED_WAITING
watcher: WAITING
blocked: BLOCKED
sleeper: TERMINATED

What this code does

  • sleep(500) gives TIMED_WAITING, lock.wait() gives WAITING, and a thread trying to enter synchronized (lock) while main holds it is BLOCKED. waitFor polls until the state appears, so the output is the same on every run.
  • The blocked thread enters the lock once main leaves the block and calls notifyAll, which wakes watcher; after the join calls every thread is TERMINATED.

The six Thread.State values: NEW (created, not started), RUNNABLE (running or ready to run), BLOCKED (waiting to enter a synchronized block), WAITING (wait(), join()), TIMED_WAITING (sleep(ms), wait(ms), join(ms)) and TERMINATED. wait() without holding the lock throws IllegalMonitorStateException.

Easy marks to remember:

  • Java has no separate "running" state: RUNNABLE covers both running and ready.
  • BLOCKED is only for synchronized; waiting for a ReentrantLock shows as WAITING.
  • interrupt() wakes a sleeping or waiting thread with InterruptedException.

Order of execution

Order one thread's life

Put the steps of a thread that starts, sleeps and finishes in order.

Callable and Future: return values and exceptions

Future<V> is a handle to a result that a task will produce later. get() waits for the result, and if the task failed it throws ExecutionException with the original error as its cause.

A task that returns a value, or fails, needs a handle. This program submits two Callable tasks, one that works and one that throws, and reads both with get().

Example 4 · Future.get, and an exception wrapped in ExecutionException

CallableFutureDemo.javaJava
import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class CallableFutureDemo {    public static void main(String[] args) throws InterruptedException {        ExecutorService pool = Executors.newFixedThreadPool(2);
        Callable<Integer> hostelA = () -> 120 * 3500;        Callable<Integer> hostelB = () -> {            int rooms = 0;            if (rooms == 0) {                throw new IllegalStateException("Hostel B has no rooms listed");            }            return rooms * 4000;        };
        Future<Integer> a = pool.submit(hostelA);        Future<Integer> b = pool.submit(hostelB);
        try {            System.out.println("Hostel A rent: " + a.get());            System.out.println("Hostel B rent: " + b.get());        } catch (ExecutionException e) {            System.out.println("Task failed: " + e.getCause().getClass().getSimpleName()                    + ": " + e.getCause().getMessage());        }        System.out.println("a done? " + a.isDone() + ", b done? " + b.isDone());        pool.shutdown();    }}
Output
Hostel A rent: 420000
Task failed: IllegalStateException: Hostel B has no rooms listed
a done? true, b done? true

What this code does

  • a.get() returns the rent computed by the Callable. b.get() throws ExecutionException, and getCause() gives the original IllegalStateException with its message.
  • A task that ended with an exception still counts as done, so isDone() is true for both.

get() blocks until the task finishes; get(timeout, unit) gives up with TimeoutException; isDone() checks without blocking; cancel(true) tries to interrupt the task. If the Callable throws, get() throws ExecutionException and getCause() holds the original exception.

Interviewers ask this because an exception in a plain Runnable thread is only printed by the default handler and is otherwise lost to the caller. A Future is how the caller finds out.

Find the bug

Find the Future bug

Click the line that is wrong.

The task divides by zero. Which line never catches the failure?

Round 1 of 2

Process vs thread; daemon threads

Daemon thread is a background helper thread, such as the garbage collector's. The JVM exits when only daemon threads are left, without waiting for them to finish.

Threads share one process. This program starts a daemon thread that loops forever and shows that it cannot keep the JVM alive.

Two threads in one program. Thread main has its own call stack with main() and printBill(); thread worker-1 has its own stack with run() and process(). Both threads point to one shared heap that holds the Order object and a counter.

Example 5 · Daemon threads do not keep the JVM alive

DaemonDemo.javaJava
public class DaemonDemo {    public static void main(String[] args) throws InterruptedException {        Thread autosave = new Thread(() -> {            while (true) {                try {                    Thread.sleep(100);               // pretend to autosave forever                } catch (InterruptedException e) {                    return;                }            }        }, "autosave");        autosave.setDaemon(true);                    // must be set before start()        autosave.start();
        System.out.println("main is daemon? " + Thread.currentThread().isDaemon());        System.out.println("autosave is daemon? " + autosave.isDaemon());        try {            autosave.setDaemon(false);        } catch (IllegalThreadStateException e) {            System.out.println("setDaemon after start: IllegalThreadStateException");        }        System.out.println("main ends; the JVM exits without waiting for autosave");    }}
Output
main is daemon? false
autosave is daemon? true
setDaemon after start: IllegalThreadStateException
main ends; the JVM exits without waiting for autosave

What this code does

  • autosave loops forever, yet the program ends as soon as main finishes, because it is a daemon thread.
  • setDaemon must be called before start(); calling it on a running thread throws IllegalThreadStateException.

A process is a running program with its own memory; a JVM is one process. Threads live inside it and share the heap (objects, static fields), but each has its own stack (local variables, method calls). Threads are cheaper to create and switch than processes, and shared memory is also the source of race conditions.

Call setDaemon(true) before start(); afterwards it throws IllegalThreadStateException. A thread inherits the daemon status of its creator, so threads made by main are user threads by default.

Next step

Check your understanding

12 quick questions