Core Java · 5. Multithreading, lesson 1 of 7

Multithreading basics: threads, Runnable and Callable

Beginner7 min read@since 8Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

Multithreading lets one program do several things at the same time: serve many web requests at once, download files while the screen stays responsive, or use every CPU core for a big calculation.

  • A process is a running program with its own memory. A thread is a path of execution inside a process, and all threads of a process share its memory (the heap).
  • Every Java program starts with one thread, main. You create more by giving a Thread a task and calling start().
  • A task is a Runnable (no result) or a Callable<T> (returns a value and may throw).
  • A thread moves through states: NEW → RUNNABLE → (BLOCKED, WAITING or TIMED_WAITING) → TERMINATED.
  • Thread.sleep(ms) pauses the current thread; join() waits for another thread to finish.

This is the first step of the multithreading track. Next: what goes wrong when threads share data (race conditions and synchronization), then the tools professionals use (thread pools, CompletableFuture, concurrent collections).

Diagram

Process vs thread

  • Process: a running program with its own memory. Processes are isolated: one crashing doesn't take others down. They talk through files, sockets or pipes, and they're expensive to create.
  • Thread: a path of execution inside a process. Threads share the process's heap (objects) but each has its own stack (local variables, method calls). They're cheap to create and switch between, and they talk simply by sharing objects.

That sharing is the whole story of multithreading: it's what makes threads fast, and it's what makes them dangerous. A bug in one thread (corrupting shared data, or running out of memory) affects the whole process.

Java
System.out.println("Process id: " + ProcessHandle.current().pid());          // Java 9+
System.out.println("Current thread: " + Thread.currentThread().getName());   // main
System.out.println("CPU cores: " + Runtime.getRuntime().availableProcessors());

Creating a thread by extending Thread

The simplest way to see a thread: extend Thread, put the work in run(), then call start(). It works, but it uses up your one superclass and mixes "what to do" with "how it runs", so the next subtopic's Runnable is preferred.

Java
class Downloader extends Thread {
    private final String url;
    Downloader(String url) { super("downloader"); this.url = url; }

    @Override public void run() {
        System.out.println(getName() + " downloading " + url);
    }
}

new Downloader("https://example.com/java.pdf").start();

Runnable: the task, separate from the thread

Runnable is a functional interface with one method, void run(). You describe what to do as a Runnable and hand it to a Thread (or later, to a thread pool). Your class stays free to extend something else, and the same task can run anywhere. Give threads names: they show up in logs and thread dumps.

Java
Runnable sendEmails = () -> System.out.println("Sending emails on " + Thread.currentThread().getName());

Thread worker = new Thread(sendEmails, "email-worker");
worker.start();                      // Sending emails on email-worker

new Thread(() -> System.out.println("Quick task")).start();   // a lambda is fine for small tasks

Callable: a task that returns a result

Callable<V> is like Runnable, but call() returns a value and may throw checked exceptions. A Thread can't take a Callable directly; wrap it in a FutureTask (a Runnable that also holds the result) or, in real code, submit it to an ExecutorService (the advanced lesson). get() waits for the result, and any exception thrown by the task arrives wrapped in an ExecutionException.

Java
Callable<Integer> countLines = () -> Files.readAllLines(Path.of("app.log")).size();   // may throw IOException

FutureTask<Integer> task = new FutureTask<>(countLines);
new Thread(task).start();

try {
    System.out.println("Lines: " + task.get());          // waits until the result is ready
} catch (ExecutionException e) {
    System.out.println("Failed: " + e.getCause());      // e.g. NoSuchFileException
}

The thread lifecycle

A thread is always in one of six states (Thread.State):

  • NEW: created, start() not called yet.
  • RUNNABLE: running, or ready to run as soon as a CPU is free.
  • BLOCKED: waiting to enter a synchronized block another thread holds.
  • WAITING: waiting with no time limit, for example in join() or wait().
  • TIMED_WAITING: waiting with a time limit, for example in sleep(ms) or join(ms).
  • TERMINATED: run() has finished, normally or with an exception.
Java
Thread t = new Thread(() -> {
    try { Thread.sleep(200); } catch (InterruptedException ignored) { }
});
System.out.println(t.getState());   // NEW
t.start();
Thread.sleep(50);
System.out.println(t.getState());   // TIMED_WAITING   (it's inside sleep)
t.join();
System.out.println(t.getState());   // TERMINATED

start() vs run()

  • start() asks the JVM to create a new thread, which then calls run(). It returns immediately, so your code carries on in parallel.
  • run() is just a normal method call on the current thread. Nothing runs in parallel.
  • A thread can be started only once; calling start() again throws IllegalThreadStateException.
Java
Thread t = new Thread(() -> System.out.println("Running on " + Thread.currentThread().getName()));

t.run();      // Running on main       just an ordinary method call
t.start();    // Running on Thread-0   a new thread
// t.start(); // IllegalThreadStateException: can't start a thread twice

sleep(): pausing a thread

Thread.sleep(ms) pauses the current thread for at least that long (the operating system may wake it slightly later).

  • It doesn't release locks: a thread sleeping inside synchronized still blocks everyone waiting for that lock.
  • It throws InterruptedException if another thread interrupts it; handle that by stopping, or by restoring the flag.
  • Don't use sleep to wait for another thread to finish; that's what join() is for.
Java
Thread.sleep(500);                         // half a second
TimeUnit.SECONDS.sleep(2);                  // more readable
Thread.sleep(Duration.ofMillis(250));       // Java 19+

// A polling loop that respects interruption:
while (!Thread.currentThread().isInterrupted()) {
    checkForNewOrders();
    try {
        Thread.sleep(1_000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();   // restore the flag; the loop condition ends the loop
    }
}

join(): waiting for a thread to finish

t.join() makes the current thread wait until t has finished. join(ms) waits at most that long. Joining also guarantees you see everything the finished thread wrote, which is why it's the simple, correct way to collect results from threads.

Java
long[] left = new long[1], right = new long[1];

Thread a = new Thread(() -> left[0] = sum(1, 500_000));
Thread b = new Thread(() -> right[0] = sum(500_001, 1_000_000));
a.start();
b.start();

a.join();                                 // wait for both halves
b.join();
System.out.println(left[0] + right[0]);   // 500000500000

static long sum(long from, long to) {
    long total = 0;
    for (long i = from; i <= to; i++) total += i;
    return total;
}

Stopping a thread politely: interrupt()

Java has no safe way to force-stop a thread: stop() was deprecated long ago, and since Java 20 it just throws UnsupportedOperationException. Instead, ask it: t.interrupt() sets a flag. Blocking calls such as sleep, join and wait react by throwing InterruptedException; other code should check Thread.currentThread().isInterrupted() regularly. Never swallow InterruptedException silently: either stop, or call Thread.currentThread().interrupt() to keep the flag for the caller.

Daemon threads

The JVM exits when all non-daemon (user) threads have finished. Daemon threads are background helpers that don't keep the JVM alive: set t.setDaemon(true) before start(). Use them for housekeeping that can be cut off at any moment (never for writing files or sending payments). Virtual threads are always daemon threads.

Example

Java
public class Kitchen {
    public static void main(String[] args) throws InterruptedException {
        Runnable makeTea = () -> {
            System.out.println("Tea started by " + Thread.currentThread().getName());
            pause(500);
            System.out.println("Tea ready");
        };

        Thread cook1 = new Thread(makeTea, "cook-1");
        Thread cook2 = new Thread(() -> System.out.println("Toast by " + Thread.currentThread().getName()), "cook-2");

        cook1.start();                 // both cooks now work at the same time
        cook2.start();

        cook1.join();                  // main waits until both have finished
        cook2.join();
        System.out.println("Breakfast served by " + Thread.currentThread().getName());   // main
    }

    static void pause(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();       // keep the interrupt flag
        }
    }
}

Common mistake

Calling thread.run() instead of thread.start(). run() executes the task on the current thread, so nothing happens in parallel.

Under the hood

Sharing memory is what makes threads fast and what makes them dangerous: two threads changing the same variable can corrupt it, which is the next lesson. The order of output between threads isn't guaranteed; run the example a few times and it can change. In real applications you rarely create threads by hand: servers and ExecutorService manage pools of threads, and since Java 21 virtual threads make one thread per task cheap.

Check yourself

Which method actually starts a new thread?

How this connects

Part of Crack the Java interview, Multithreading: beginner to advanced.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.