Stop 12 · Multithreading & JVM InternalsTopics · 1/9

Threads & Runnable

Part of the Java Roadmap

In short

Your laptop has many CPU cores, but a plain Java program uses one path of execution. Threads let one program do several things at once, like downloading a file while the screen stays responsive.

A thread is a separate path of execution. You create one by passing a Runnable (often a lambda) to a Thread and calling start(). Calling run() directly does not start a new thread.

The jaadu hands three small recipe cards to three little cooks at three separate stoves in a busy dhaba kitchen, each stove with a different pot bubbling.

Think of it like this

Cooks in one kitchen

A dhaba with one cook makes dal, then rotis, then chai, one after another. Hire three cooks and all three dishes are made at the same time in the same kitchen. Each cook is a thread, the recipe card you hand them is the Runnable, and saying "start cooking" is start().

Watch it happen

main starts two worker threads

main
worker-1
worker-2

start()

1/6main creates a Thread with a Runnable and calls start(). The JVM schedules a new thread.

The big ideas

What you need to know

Runnable is the job

Runnable has one method, run(), with no return value. A lambda like () -> download(url) is a Runnable.

start(), not run()

start() creates a new thread that then calls run(). Calling run() directly just runs it on the current thread.

join() waits

t.join() makes the calling thread wait until t finishes. Use it when you need the worker's result before going on.

Order is not guaranteed

The OS scheduler decides which thread runs when. Never write code that depends on threads finishing in a particular order.

See it in code

Walk through the code

java
1public class Downloader {2    public static void main(String[] args) throws InterruptedException {3        Runnable job = () -> {4            String name = Thread.currentThread().getName();5            System.out.println(name + " downloading...");6        };7 8        Thread t1 = new Thread(job, "worker-1");9        Thread t2 = new Thread(job, "worker-2");10 11        t1.start();12        t2.start();13 14        t1.join();15        t2.join();16        System.out.println("All downloads finished");17    }18}

1/4The job, written as a lambda. It prints the name of whichever thread runs it.

Two threads run the same Runnable. Run it a few times and the first two lines may swap places.

Save yourself the pain

Common mistakes

Oops

Calling t.run() and expecting it to run in parallel.

Do this instead

Call t.start(). run() is an ordinary method call on the current thread.

Oops

Extending Thread for every task.

Do this instead

Implement Runnable (or use a lambda) and pass it to a Thread or an executor. It keeps the task separate from how it runs.

Oops

Calling start() twice on the same Thread object.

Do this instead

A thread can be started only once. The second call throws IllegalThreadStateException. Create a new Thread instead.

Your mission

Race the counters

~20 min

Quick check

What happens when you call run() on a Thread object instead of start()?

Go deeper

  1. 1Start two threads that print messages and observe the interleaving.
  2. 2Use join() to wait for a thread to finish.
  3. 3Learn the thread lifecycle states: NEW, RUNNABLE, BLOCKED, WAITING and TERMINATED.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge