Doing several things in one program
A program normally runs one instruction after another, along a single path. Threads let one program follow several paths at once. A text editor might use one thread to respond to your typing while another saves a backup in the background, so the window never freezes. Think of a restaurant kitchen: the cooks are threads, all working in the same kitchen and grabbing ingredients from the same fridge.
That shared fridge is the key detail. Threads in one program share memory, which makes passing data between them cheap but also risky. If two threads update the same variable at the same moment, one change can be lost. This is called a race condition, and locks (also called mutexes) exist to prevent it.
Starting threads in Java
public class Demo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> System.out.println("Hello from worker"));
worker.start();
System.out.println("Hello from main");
worker.join(); // wait for the worker to finish
}
}
The two messages can print in either order, because the threads run independently.
Thread vs process
A process is a whole running program with its own private memory. Threads live inside a process and share its memory. Starting a thread is cheaper than starting a process, and threads communicate more easily, but a crash or memory bug in one thread can bring down the entire process.
Language implementations matter too. In standard CPython, the Global Interpreter Lock (GIL) lets only one thread execute Python bytecode at a time, so threads speed up waiting on files or networks but not heavy number crunching. Python developers often reach for multiple processes when work is CPU-bound. Since Python 3.13, an optional free-threaded build without the GIL is available.
JavaScript takes another path: your code runs on a single thread with an event loop, and Web Workers or Node's worker threads handle extra work separately.
Learn more
Last updated