Multithreading in Java: Processes and Threads
Multithreading is the concurrent execution of several threads inside a single process. A thread is an independent sequence of instructions with its own call stack; all threads of a process work with the same shared memory (the heap), so they can process the same data together. In Java, multithreading is built into the language: a thread is represented by the java.lang.Thread class, and every program starts with at least one thread, main.
Plenty of tutorials and lecture notes still repeat the rule “a program ends when the main thread ends.” It's wrong: main can finish while the program keeps running for another minute. Why that happens, and when the JVM actually stops, is shown in The main thread.
Multitasking: Process-Based and Thread-Based
Multitasking is a system's ability to run several tasks at the same time. It comes in two kinds: process-based (different programs run side by side) and thread-based (one program performs several tasks). Multithreading is the second kind.
Process-based multitasking
Process-based multitasking lets a computer run two or more programs at once. A process is, essentially, a program that is running. Processes are heavyweight tasks, and each one needs its own address space. Communication between processes is limited and expensive. Switching the context from one process to another is expensive too. A process can have several threads, and the number of threads can change while the process runs.
Thread-based multitasking
Thread-based multitasking means that a single program can perform two or more tasks at the same time. Threads are lighter than processes. They share one address space and belong to one process. Communication between threads is cheap, and so is switching the context from one thread to another.
A real-world example is a web browser. Each tab often runs in a separate process: if one tab crashes, the others survive. Inside a tab, different threads load images, run scripts and render the page at the same time, exchanging data through shared memory.
Process vs Thread: What’s the Difference
A process is a running program with its own isolated memory; a thread is a unit of execution inside a process that shares memory with the other threads of the same process. That's why threads are cheaper to create and easier to connect, but a bug in one thread can corrupt data for all the others.
| Criterion | Process | Thread |
|---|---|---|
| Memory | Its own address space; can't see another process's memory directly | Shares the process heap; only the stack is its own |
| Creation | Expensive: the OS allocates memory and loads the program; for Java, a new JVM starts | Cheaper: a stack and an OS structure (even cheaper for virtual threads) |
| Context switch | Expensive: the address space changes | Cheaper: memory is shared, only registers and the stack are saved |
| Communication | Through OS facilities: files, sockets, pipes | Through shared objects on the heap — fast, but needs synchronization |
| Fault isolation | A crashed process doesn't affect the others | Corrupted shared data is seen by every thread; OutOfMemoryError or System.exit() affect the whole JVM |
| What it is in Java | A running JVM; a new process is started with ProcessBuilder | A Thread object started with start() |
Fault isolation has a twist that people often don't expect. An uncaught exception in Java ends only the thread it was thrown in: the console shows Exception in thread "Thread-0" ..., and the other threads, main included, carry on as if nothing happened. The program doesn't crash, but part of the work silently never gets done.
Multithreading in Java: What Threads Share and What Each Owns
Threads of one Java process share the heap with all its objects, static fields and the process's resources, while each thread has its own stack with local variables. That gives the core rule of multithreaded code: anything on the heap that several threads can reach needs protection; a method's local variables don't.
Java implements multitasking on the basis of threads. Multithreaded programming is used to minimize system idle time, because several tasks can run at the same time. In Java the word “thread” refers to two different things: a thread of execution and an object of the java.lang.Thread class. You can create the object and never start it; the thread of execution appears only after start() is called.
Threads share:
- class variables and static variables;
- the dynamically allocated memory (the heap), and therefore every object they hold references to;
- system resources allocated to the process: open files, network connections.
Each thread has its own local variables, that is, its own stack: it holds method calls, their parameters and local variables. Each thread also has its own program counter — the place in the code it is executing right now. That's why two threads can run the same method at the same time, each with its own copy of the local variables.
The main Thread and When a Program Ends
When a Java program starts, the JVM creates the main thread, which runs the main() method. The program doesn't end together with it: it ends when all non-daemon threads have finished (or when someone calls System.exit()). The main thread can be the first one to finish.
When a Java program starts, the main thread (main) begins to run. From it the program spawns the other threads — directly or through threads it has already created: a new thread can be started from any thread. Unlike the threads created later, the main thread is created automatically. It's often identified with the program itself, but that's not accurate:
public class MainEndsFirst {
public static void main(String[] args) {
Thread worker = new Thread(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Thread " + Thread.currentThread().getName() + " finished");
});
worker.start();
System.out.println("Thread main finished");
}
} Thread main finished
Thread Thread-0 finished The first line appears immediately, the second two seconds later. During that time main() has already returned, yet the JVM keeps running because Thread-0 is not a daemon thread. Call worker.setDaemon(true) before start(), and the second line never prints: when only daemon threads remain, the JVM exits without waiting for them. The same rule is briefly covered in the FAQ of Runnable and Thread in Java.
How to Create a Thread in Java
There are two ways to create a thread in Java: extend the java.lang.Thread class or implement the java.lang.Runnable interface (the preferred option). In both cases you override the run() method and start the thread with start(). The shortest form is new Thread(() -> ...).start().
How the two approaches differ, why calling run() instead of start() doesn't create a new thread, and which constructors Thread has are covered in Runnable and Thread in Java: How to Create a Thread.
Concurrency vs Parallelism
Concurrency means several tasks are in progress during the same period of time, but they may run in turns, a slice at a time. Parallelism means tasks literally run at the same instant on different CPU cores. Parallelism is a special case of concurrency.
A multithreaded program on a single-core CPU is concurrent but not parallel: the scheduler switches the core between threads quickly enough to create the illusion of simultaneous work. On a multi-core CPU the same threads can run in parallel. For your code the difference barely matters — synchronization bugs show up in both cases, because a thread can be interrupted between any two instructions. Speeding up computation, though, takes real parallelism.
In interviews this question often comes paired with an example: a web server handling hundreds of connections on one core is concurrency; parallelStream() spreading the sum of a large array across all cores is parallelism.
Why Use Multithreading, and When It Doesn’t Help
Multithreading exists to avoid idling: while one thread waits for the network, the disk or the user, others keep working, and computations can be spread across CPU cores. You get a speedup only if the task really waits on I/O, or if there are enough free cores for all the compute threads.
It helps to split tasks into types:
| Task type | Example | What multithreading gives you |
|---|---|---|
| I/O-bound — spends most of its time waiting for I/O | HTTP requests, database calls, reading files | A big win: while some threads wait for a response, others send requests. You can have far more threads than cores |
| CPU-bound — constantly busy computing | Compression, image processing, math over large arrays | Speedup no greater than the number of cores. Threads beyond the core count only add switching |
| Inherently sequential | Each step depends on the result of the previous one | None: the work can't be split, only the overhead remains |
One line tells you how many cores the JVM sees:
System.out.println(Runtime.getRuntime().availableProcessors());
// Output: 8 (depends on the machine; in a container, the container's CPU limit) Threads have a cost. Every platform thread takes memory for its stack, creating one is a system call, and every context switch saves and loads thread state and “cools down” the CPU cache (details in Context Switching in Java). On top of that comes synchronization: if threads keep waiting for each other on shared data, they sit idle, and the multithreaded version can turn out slower than the single-threaded one.
More threads doesn’t mean faster
On a 4-core CPU, 100 threads won't make a compute-heavy task faster than four threads would: only four run at any moment, and the other 96 just add context switches. Before you parallelize, figure out what your task is waiting for — the CPU or I/O.
What Problems Multithreading Brings
Shared memory, the very thing that makes threads convenient, is also the source of the main bugs in multithreaded code: lost updates in a race, stale values due to visibility issues, deadlocks and starvation. The compiler doesn't catch them, and they often reproduce only once in a while.
| Problem | What happens | Where it’s covered |
|---|---|---|
| Race condition | Threads modify shared data at the same time, and some of the changes are lost | Thread synchronization: race condition |
| Visibility | A thread doesn't see a write made by another thread, or sees it late | synchronized and visibility: happens-before |
| Deadlock | Threads wait forever for resources held by each other; the program hangs with no exception | Deadlock in Java |
| Starvation | A thread goes a long time without getting the CPU or a resource because others keep taking it | Priorities and starvation |
| Livelock | Threads are busy, but keep yielding to each other forever and make no progress | Deadlock, livelock and starvation |
All of these bugs share one nasty trait: the result depends on how the scheduler interleaves the threads. A test that passed a hundred times can fail on the hundred-and-first run, and a bug seen on the server won't reproduce on the developer's machine. That's why multithreaded code is designed to keep shared mutable state to a minimum — the approaches are collected in Thread Safety in Java.
Platform and Virtual Threads (Java 21)
Since Java 21 (JEP 444) there are two kinds of threads. A platform thread is a wrapper around an operating system thread: it is expensive, its stack reserves about a megabyte by default, and thousands of them are already a burden. A virtual thread is managed by the JVM itself and runs on top of a small number of platform carrier threads, so you can create hundreds of thousands of them.
Virtual threads shine on I/O-bound work such as “one thread per request” (Executors.newVirtualThreadPerTaskExecutor()), but they don't speed up computation: they don't add cores. Every synchronization rule in this module applies to them as well. How to create a virtual thread is shown in Thread.ofPlatform() and Thread.ofVirtual().
How to Learn Multithreading: Module Plan
A Java multithreading tutorial works best in this order: first creating threads and their life cycle, then the control methods (sleep(), yield(), join()), then synchronization and what goes wrong with it, and finally communication between threads and thread-safe classes. Each lesson builds on the previous ones.
- Multithreading in Java: Processes and Threads (this lesson) — what a thread is, how it differs from a process, the main thread, which tasks multithreading speeds up.
- Runnable and Thread: How to Create a Thread — the two ways to create a thread, lambdas,
start()vsrun(), thread names,Thread.ofVirtual(). - Thread States: the Thread Life Cycle — the six values of
Thread.State, the transition diagram,BLOCKEDvsWAITING. - Thread Priority and the Scheduler —
setPriority(), who actually picks the thread, context switching, what Java guarantees. - Thread.sleep() — how to pause a thread,
InterruptedException,sleep()vswait(). - Thread.yield() — a hint to the scheduler to give up the CPU, and how it differs from
sleep(). - Thread.join() and isAlive() — how to wait for another thread to finish, timeouts.
- Thread Synchronization: synchronized and Monitors — race conditions, the monitor,
volatile, visibility of changes. - Deadlock in Java — the conditions for a deadlock, how to avoid it and how to find it with
jstack. - wait(), notify() and notifyAll(): Inter-Thread Communication — Producer–Consumer, spurious wakeups,
IllegalMonitorStateException. - Thread Safety: Thread-Safe Classes and Collections — immutable classes,
AtomicInteger, concurrent collections.
If you're preparing for an interview, the multithreading questions that come up most often are process vs thread, start() vs run(), thread states, synchronized and volatile, deadlock, and wait()/notify() — that is, lessons 1, 2, 3, 8, 9 and 10 on this list.
Frequently Asked Questions
Are multithreading and multitasking the same thing?
No. Multitasking is the general idea: a system runs several tasks at once. It can be process-based (several programs) or thread-based (several tasks inside one program). Multithreading is the second kind — multitasking within a single process. More in Multitasking.
Why does Java use threads rather than several processes?
Because threads of one process see the same objects on the heap and can exchange data without serialization or OS facilities, and they're cheaper to create and switch. Separate processes (ProcessBuilder) are used when you need isolation, so that a crash or a memory leak in one part doesn't take down the rest. A point-by-point comparison is in the Process vs Thread table.
How many threads should I create?
For compute-heavy tasks, about as many as there are cores: Runtime.getRuntime().availableProcessors(). For tasks that wait on I/O, more; a well-known estimate from “Java Concurrency in Practice” is number of cores × (1 + wait time / compute time). The exact value is tuned by measuring under load. For thousands of concurrent requests on Java 21, the usual choice is virtual threads rather than a huge pool of platform threads.
What's the difference between multithreading and asynchronous programming?
Multithreading is about how many threads do the work. Asynchronous programming is about the caller not waiting for the result and getting it later: through a callback, a Future or a CompletableFuture. Asynchronous code can run in other threads (CompletableFuture.supplyAsync() uses ForkJoinPool.commonPool() by default), or in a single thread with an event loop, as in Netty or JavaScript.
Comments