Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 12 / Topic 1 of 7

Thread and Runnable

A thread is an independent line of execution inside one running JVM process — your main method already runs on one (the "main thread"). Starting more threads lets independent pieces of work actually overlap in time instead of waiting for each other. Think of a sweet shop with one counter versus three: one counter serves customers one at a time, however fast it works; three counters serve three customers at once.

Runnable is a functional interface — just one method, run(), with no return value and no checked exceptions. A Thread wraps a Runnable and gives it somewhere to run.

Runnable task = () -> prepareOrder(sweet, 150);   // Runnable: just the job, no Thread machinery yet
Thread counter = new Thread(task, "counter-" + sweet);
counter.start();          // runs in the background from here on -- NOT counter.run()!
counter.join();            // wait here until this thread finishes
$ javac ThreadBasics.java
$ java ThreadBasics
== one order at a time ==
ready: ladoo
ready: jalebi
ready: barfi
sequential took at least 450 ms: true

== three counters at once, with Thread + Runnable ==
ready: ladoo
ready: barfi
ready: jalebi
threaded took less than 450 ms: true

== a thread's name and priority-free identity ==
billing-worker is running

== a daemon thread: stopped automatically when main ends ==
is daemon: true
main program ends now; the daemon dies with it, never printing anything

Three sweets at 150 ms each take at least 450 ms run one after another, and well under that run as three threads — the three Thread.sleep calls overlap instead of stacking up. Note counter.start(), never counter.run(): calling run() directly just executes the method on the current thread, like calling any other method — start() is the one call that actually hands the work to a new thread. counter.join() blocks the calling thread until that one finishes, which is how main waits for background work instead of racing ahead of it.

The sweets finished out of submission order (ladoo, then barfi, then jalebi) — the JVM and OS decide thread scheduling, and that order is not guaranteed to match the order threads were started in.

A daemon thread (setDaemon(true), set before start()) doesn't keep the JVM alive on its own — when every non-daemon thread finishes, the JVM exits immediately, daemon threads and all, mid-task if need be. A plain background Thread left running would keep the program alive forever; a daemon thread is the deliberate opposite, used for truly background work (like a heartbeat) that should never block shutdown.

Full program: examples/ThreadBasics.java.

Done here? The practice set for Part 12 — including the solutions — is on the part page.

Search the guide