Skip to content
Tutorials Center
My learning

Topics

Lesson 125 of 201 ยท Concurrency

Threads

Learn Java threads - processes vs threads, creating threads with Thread and Runnable, start vs run, join, sleep, thread names, daemon threads and thread exceptions.

So far every program in this course has done one thing at a time: one statement, then the next. A thread is an independent path of execution, and a Java program can run many of them at once. A web server handles each request on its own thread; a desktop app keeps its window responsive while a download runs in the background; a batch job splits a big calculation across every CPU core.

Threads are powerful and easy to start, but they are also the source of the trickiest bugs in programming, because threads share memory. This lesson covers the basics: creating, starting, naming, waiting for and stopping threads. The following lessons tackle sharing data safely (Synchronization) and the higher-level tools you'll use in real code (Executors, Virtual Threads).

Why use multiple threads?

  • Better performance. On a computer with several CPU cores, a job split across threads finishes sooner, because the cores work at the same time.
  • Responsiveness. A user interface can keep reacting to clicks while another thread does slow work such as a download or a database query.
  • Waiting without wasting time. While one thread waits for a file or a network reply, other threads keep the CPU busy. A server that handles each client on its own thread serves many clients at once.
  • Simpler models. "One thread per task" is often the clearest way to express independent activities, such as one thread per connection.
  • Resource sharing. Threads share the heap, so they can work on the same data without copying it. The price is that shared data needs the care described in Synchronization.

Threads also cost something: memory for each stack, time for switching between them, and bugs from races and deadlocks. Use them when the benefit is real.

Processes and threads

A process is a running program with its own memory. Starting a JVM creates one process. Processes are isolated from each other; one can't read another's variables.

A thread lives inside a process. All threads of a process share the same heap (objects, static fields), but each has its own stack for local variables and method calls, and its own position in the code. Threads are cheaper to create than processes and can communicate simply by sharing objects, which is both their strength and their danger.

Even the simplest Java program runs on a thread: main executes on a thread called main, and the JVM runs a few extra threads in the background (for garbage collection and JIT compilation, for example).

Java The main thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Thread.currentThread() returns the thread that is executing that line. You'll use it a lot to see which thread is doing what. (threadId() replaced the older getId() in Java 19.) availableProcessors() tells you how many threads can run truly in parallel; with more threads than cores, the operating system switches between them very quickly, so they still appear to run at the same time. (Our online editor limits each program to one core, so it prints 1 here; your own computer will report more.)

Creating and starting a thread

A thread needs a task, which is a Runnable: an interface with a single method, void run(). Because Runnable is a functional interface, a lambda works. You pass the task to a Thread and call start():

Java Starting threads three ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Run it a few times. The lines from the three threads can come out in a different order each run, because the operating system decides when each thread actually runs. Only "All done" is guaranteed to be last, because main waits for every thread with join() first. Never write code that depends on threads running in the order you started them.

Which way should you use?

  • Lambda or Runnable: the normal choice. The task is separate from the thread that runs it, so the same task can later go to a thread pool without changes, and your class is free to extend something else.
  • Subclassing Thread: only when you're genuinely customizing the thread itself, which is rare. It mixes "what to do" with "how to run it".

Since Java 21 there is also a builder API, handy for naming threads:

Java
Thread t = Thread.ofPlatform().name("worker-", 1).start(() -> doWork());   // "worker-1"
Thread v = Thread.ofVirtual().start(() -> doWork());                        // a virtual thread

Virtual threads are lightweight threads for running thousands of tasks at once; everything in this lesson applies to them too.

start() versus run()

This is the most common beginner mistake with threads. start() creates a new thread, which then calls run(). Calling run() yourself is just an ordinary method call on the current thread:

Java run() does not start a thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first line of output says main, the second says my-worker. A Thread object is also single-use: once started, it can never be started again, even after it finishes. To run the task again, create a new Thread.

Waiting with join() and pausing with sleep()

t.join() blocks the calling thread until t finishes. join(millis) waits at most that long, so you can stop waiting for a thread that hangs. Thread.sleep(millis) pauses the current thread. Both throw the checked InterruptedException, which the next lesson explains; for now, main simply declares it.

Here's why threads matter: two tasks that each wait 300 ms take about 600 ms one after the other, but about 300 ms when they wait at the same time.

Java Sequential versus concurrent work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Sleeping stands in for real waiting: network calls, database queries, disk reads. This is the most common reason to use threads in server code. CPU-heavy work speeds up too, but only up to the number of cores.

Thread.sleep is a minimum, not a precise timer: the thread wakes up at least that much later, often a little more. Never use sleep to "wait until the other thread is probably done". That is a race; use join() or the coordination tools from later lessons.

Getting results back from threads

run() returns void, so a thread can't simply return a value. With plain threads, a simple safe pattern is to give each thread its own slot to write into and read the slots only after join():

Java Splitting a sum across threads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two things make this correct. Each thread writes only its own array element, so no two threads touch the same variable. And join() guarantees that everything the finished thread wrote is visible to the thread that joined it. Without that guarantee, main could read stale values. If several threads updated one shared total instead, you'd get a race condition, the subject of Synchronization and Race Conditions.

In real code you'd usually submit Callable tasks to an ExecutorService and collect Future results (Executors and Thread Pools), or use a parallel stream. The manual version shows what those tools do for you.

Daemon threads

The JVM exits when all non-daemon threads have finished. Normal threads are non-daemon, so if main ends while a worker is still running, the program keeps going until the worker finishes too.

A daemon thread is a background helper that doesn't keep the JVM alive: when the last non-daemon thread ends, daemon threads are simply stopped, wherever they are. Mark a thread as a daemon with setDaemon(true) before start():

Java A daemon thread is stopped when main ends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You'll see about four heartbeats (the exact count can vary by one), then the program ends even though the loop is infinite. Remove setDaemon(true) and the program would never finish on its own (here it would be stopped by the time limit).

Because daemon threads are cut off without warning, finally blocks in them may never run. Don't use them for work that must complete, such as writing a file. A new thread inherits the daemon status of the thread that created it.

Names and uncaught exceptions

Give threads meaningful names. They appear in stack traces, logs, debuggers and thread dumps, and Thread-7 tells you nothing when a production system misbehaves.

If an exception escapes run(), only that thread dies; the rest of the program continues. By default the JVM prints the stack trace to standard error with the thread's name. You can install your own handler to log it properly:

Java An exception kills only its own thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first thread uses a custom handler. The second has none, so you'll see the default message Exception in thread "no-handler" java.lang.IllegalStateException: boom on standard error. Either way, main carries on. That's a trap in real systems: a worker thread can die silently while the rest of the app keeps running, so always make sure failures in background threads are logged. Thread.setDefaultUncaughtExceptionHandler(...) sets a handler for every thread that has none.

Stopping a thread

There is no safe way to force a thread to stop. The old Thread.stop() method was deprecated decades ago because it killed threads in the middle of updates, leaving objects broken, and it now simply throws UnsupportedOperationException. Instead, a thread stops cooperatively: it finishes run() when it's asked to. The standard way to ask is an interrupt, covered in Thread Lifecycle and Priorities.

The thread scheduler, ThreadGroup and deprecated methods

Who decides which thread runs?

You never choose which thread runs next. The thread scheduler does. For platform threads, Java hands the job to the operating system's scheduler: each Java thread is one OS thread, and the OS gives threads slices of CPU time (time slicing) across the available cores. Java's setPriority is only a hint that most operating systems largely ignore (see Thread Lifecycle and Priorities). Virtual threads are different: the JVM schedules them itself onto a small pool of carrier threads (see Virtual Threads).

What follows from this is the rule you already met: order between threads is never guaranteed. Thread.yield() merely suggests that the current thread is willing to let others run; the scheduler may ignore it. Code that is "correct only when the scheduler cooperates" is broken code that hasn't failed yet. Use join, locks, latches or queues to create order on purpose.

Thread groups and snapshots of all threads

A ThreadGroup is a legacy way to organize threads into a tree. Every thread belongs to one; the JVM starts with a main group under a system group. Groups once promised bulk operations and security checks, but most of that has been removed or deprecated, and today they are useful mainly for inspection:

Java Thread groups and every live thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

getThreadGroup(), activeCount() and enumerate() give you a snapshot: the numbers are estimates because threads start and finish while you count. Thread.getAllStackTraces() returns a map from every live platform thread to its current stack, which is how a monitoring page or a debug endpoint can show "what is everything doing right now". The same information is what jstack and thread dumps show (see Thread Lifecycle and Priorities). Do not build application logic on ThreadGroup; prefer an executor with a named thread factory.

Why suspend(), resume() and stop() were deprecated

Early Java let one thread freeze, revive or kill another from the outside. All three were found to be unsafe by design:

  • stop() throws a ThreadDeath error inside the target at an arbitrary point, releasing every lock it holds mid-update. Other threads then see half-modified objects (a bank transfer that debited one account but never credited the other). Since Java 20, Thread.stop() simply throws UnsupportedOperationException.
  • suspend() freezes a thread while it still holds its locks. If the thread that would call resume() needs one of those locks, both wait forever: a deadlock with no cycle you can see in your code. Modern JDKs have removed them or make them throw UnsupportedOperationException.
  • resume() exists only to undo suspend(), so it goes too.

The replacement is always cooperation: the target thread checks a flag or its interrupt status at safe points and shuts down cleanly itself, or it waits on a condition (wait/notify, Lock/Condition, a BlockingQueue) that another thread signals. That way the thread decides where it is safe to pause or stop, releases its locks properly, and leaves data consistent.

Java Cooperative pause and stop (the safe replacement)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The worker pauses only at the top of its loop, where it holds no half-finished work. wait() releases the monitor, so resume() can always get in, the deadlock that made suspend() dangerous. stop() is a flag plus a notify, so a paused thread wakes up and exits through normal code. This is the pattern behind every "pause" and "cancel" button you will ever build. See Wait and Notify.

If you ever see thread.stop(), suspend() or resume() in old code, treat it as a bug to fix, not a style issue. Also avoid ThreadGroup.stop and ThreadGroup.suspend, which were removed for the same reasons.

Common mistakes

  • Calling run() instead of start(). No new thread is created.
  • Assuming order. Threads interleave unpredictably; only explicit coordination (join, locks, queues) creates order.
  • Reading results without join(). The other thread may not be done, and its writes may not be visible yet.
  • Sharing a counter or collection between threads without synchronization. See the next lessons.
  • Creating a thread per small task in a loop. Platform threads cost memory (each has a stack) and time to create. Use a pool or virtual threads for many tasks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is printed by Thread t = new Thread(() -> System.out.println(Thread.currentThread().getName()), "w"); t.run(); when called from main?

    run() is a plain method call, so the lambda executes on the calling thread, which is main. Only start() creates the new thread named w.
  2. 2. Two threads each print three lines. What can you say about the output order?

    The scheduler decides when each thread runs. Within one thread, statements run in program order, but there is no ordering between threads without coordination.
  3. 3. main starts a non-daemon thread that loops for 5 seconds, then main returns immediately. What happens?

    The JVM exits only when all non-daemon threads have ended. Only daemon threads are stopped automatically when the last non-daemon thread ends.
  4. 4. A worker thread throws an uncaught RuntimeException. What happens to the rest of the program?

    Uncaught exceptions end only the thread they occur in. By default the stack trace is printed to stderr, which makes silent failures of background threads easy to miss.
  5. 5. Why does the parallel sum example store results in partialSums[index] instead of adding to one shared long total?

    Each thread owns one slot, so there is no conflict. A shared total updated by several threads with += would be a race condition, and a local variable cannot be modified from a lambda anyway.

Summary

  • A process has its own memory; its threads share the heap but each has its own stack. main runs on the thread named main.
  • Create a thread with a Runnable (usually a lambda) and call start(). Calling run() executes on the current thread. A Thread can be started only once.
  • join() waits for a thread to finish and makes its writes visible; sleep() pauses the current thread for at least the given time.
  • Thread output order is unpredictable; never rely on it.
  • The JVM exits when all non-daemon threads finish; daemon threads are stopped abruptly.
  • Name your threads, and handle uncaught exceptions so background failures don't go unnoticed. Threads stop cooperatively, never by force.

Next: Thread Lifecycle and Priorities, where you'll watch threads move through their states and learn to interrupt them properly.