Thread vs Runnable vs Callable
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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(); }}marks-thread total: 233 fee-thread total: 57000 Callable result: OTP-104821
What this code does
MarksThreadextendsThread; the fee task is aRunnablelambda passed tonew Thread; the OTP task is aCallablesubmitted to an executor, which returns aFuture.join()waits for both threads beforemainreads their results, andotp.get()waits for theCallable. Withoutjointhe 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.Threaditself implementsRunnable; 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()
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"); } }}run() executed on: main start() executed on: worker Second start(): IllegalThreadStateException
What this code does
t.run()ran onmain, the current thread, because it is an ordinary method call.u.start()created a new thread namedworker, which calledrun().- Starting
ua second time throwsIllegalThreadStateException, 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().
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.
Example 3 · Seeing NEW, TIMED_WAITING, WAITING, BLOCKED and TERMINATED
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); }}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 entersynchronized (lock)whilemainholds it is BLOCKED.waitForpolls until the state appears, so the output is the same on every run.- The
blockedthread enters the lock oncemainleaves the block and callsnotifyAll, which wakeswatcher; after thejoincalls 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 aReentrantLockshows as WAITING. interrupt()wakes a sleeping or waiting thread withInterruptedException.
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
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(); }}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 theCallable.b.get()throwsExecutionException, andgetCause()gives the originalIllegalStateExceptionwith 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 2Process 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.
Example 5 · Daemon threads do not keep the JVM alive
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"); }}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
autosaveloops forever, yet the program ends as soon asmainfinishes, because it is a daemon thread.setDaemonmust be called beforestart(); calling it on a running thread throwsIllegalThreadStateException.
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