Skip to lesson

A shopping app downloads a receipt, updates the screen and answers a tap, all at the same moment. If the program could do only one thing at a time, it would freeze. How does it manage?

Program, process and thread

A thread is a single path of execution inside a program. A program can run several threads at the same time, each with its own stack but sharing the same heap.

A thread is one path of execution inside a running program: a list of statements the computer carries out one after another, with its own call stack.

Two threads in one program. Thread main has its own call stack with main() and printBill(); thread worker-1 has its own stack with run() and process(). Both threads point to one shared heap that holds the Order object and a counter.

Example 1 · A running program is a process with a main thread

ProcessAndThreadDemo.javaJava
public class ProcessAndThreadDemo {    public static void main(String[] args) {        long pid = ProcessHandle.current().pid();        String threadName = Thread.currentThread().getName();
        System.out.println("Process id : " + pid);        System.out.println("Thread name: " + threadName);    }}
Sample output
Process id : 14872
Thread name: main

What this code does

  • ProcessHandle.current().pid() (Java 9+) asks the operating system for this process's id number. It changes on every run, which is why the output is a sample.
  • Thread.currentThread().getName() is always main here: the JVM ran main on its first thread, and nothing else was started.

A program is code saved on disk, such as Billing.class. A process is a program that is running: the operating system gives it its own memory and an id number. Run java Billing in two terminals and you get two separate processes.

A call stack is the list of methods a thread is inside right now, such as main → printBill. Every process has at least one thread, and it can have many. All threads of one process share the same objects in memory (the heap), but each thread keeps its own call stack and local variables.

Sharing the heap makes threads cheap and fast to work together. It is also why two threads changing the same object need care, which the Race Conditions module covers.

One counter or many: the bank picture

Picture a bank branch. With one counter, one clerk serves a customer, waits for the system to confirm the request, and only then calls the next customer. Most of that time is spent waiting, not working.

Example 2 · One counter versus three counters

BranchDemo.javaJava
class Counter implements Runnable {    private final String customer;
    Counter(String customer) {        this.customer = customer;    }
    public void run() {        BranchDemo.serve(customer);    }}
public class BranchDemo {    // Confirming a request: the counter only waits, like a program waiting for the network.    // try/catch around sleep is explained in "Pause and wait: sleep and join".    static void serve(String customer) {        try {            Thread.sleep(100);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    static long roundDown100(long ms) {        return ms / 100 * 100; // drop the extra few ms: 312 -> 300    }
    public static void main(String[] args) throws InterruptedException {        String[] customers = {"Asha", "Ravi", "Meena"};
        long start = System.currentTimeMillis();        for (String c : customers) {            serve(c);        }        long oneCounter = System.currentTimeMillis() - start;
        start = System.currentTimeMillis();        Thread[] counters = new Thread[customers.length];        for (int i = 0; i < customers.length; i++) {            counters[i] = new Thread(new Counter(customers[i]), "counter-" + (i + 1));            counters[i].start();        }        for (Thread c : counters) {            c.join();        }        long threeCounters = System.currentTimeMillis() - start;
        System.out.println("One counter   : about " + roundDown100(oneCounter) + " ms");        System.out.println("Three counters: about " + roundDown100(threeCounters) + " ms");    }}
Sample output
One counter   : about 300 ms
Three counters: about 100 ms

What this code does

  • With one counter the three 100 ms waits happen one after another, so the total is about 300 ms. With three threads the waits overlap, so the total is about 100 ms.
  • This is a preview: Runnable, new Thread(...), start() and join() are explained line by line in the next lessons. Times differ on each run and are higher on a busy computer, so the program rounds them down to a multiple of 100.

With three counters, three clerks serve at once. Each counter is like a thread: it runs its own list of steps. The branch is the process, and the shared records are the shared memory. Programs use more than one thread for two main reasons. A thread can keep working while another thread waits for a file, a network reply or a user click. And several threads can use several CPU cores at once.

Concurrency versus parallelism, and CPU cores

Concurrency means several tasks are in progress during the same period of time. They may take turns on one CPU core, switching so quickly that they look simultaneous. Parallelism means tasks really run at the same instant, on different cores.

Example 3 · How many cores does this computer have?

CoresDemo.javaJava
public class CoresDemo {    public static void main(String[] args) {        int cores = Runtime.getRuntime().availableProcessors();
        System.out.println("CPU cores available to Java: " + cores);        System.out.println("Threads that can run at the same instant: up to " + cores);        System.out.println("Any extra threads take turns on these cores.");    }}
Sample output
CPU cores available to Java: 8
Threads that can run at the same instant: up to 8
Any extra threads take turns on these cores.

What this code does

  • availableProcessors() returns how many cores (logical processors) the JVM may use. Your number depends on your computer.
  • That number is the limit for parallelism. Concurrency has no such limit: 100 threads can be in progress on 8 cores by taking turns.

A CPU core is one unit inside the processor that runs one thread at a time. A laptop with 8 cores can run up to 8 threads truly in parallel; any extra threads take turns. One server switching between three orders is concurrency; three clerks at three counters is parallelism. Java threads always give you concurrency. Whether they also run in parallel depends on how many cores are free, and the operating system decides that, not your code.

Threads that mostly wait (for the network, a file or sleep) help even on one core, because a waiting thread does not use the CPU.

The main thread every program starts with

When you run java MyApp, the JVM creates a thread named main and calls your main method on it. Every program you have written so far ran on this one thread.

Example 4 · Methods called from main run on main

MainThreadDemo.javaJava
public class MainThreadDemo {    static void printBill(String item, int price) {        String who = Thread.currentThread().getName();        System.out.println(who + " prints bill: " + item + ", Rs " + price);    }
    static void takeOrder(String item, int price) {        String who = Thread.currentThread().getName();        System.out.println(who + " takes order: " + item);        printBill(item, price);    }
    public static void main(String[] args) {        Thread current = Thread.currentThread();        System.out.println("Running on: " + current.getName());        System.out.println("Alive: " + current.isAlive());
        takeOrder("Keyboard", 60);        takeOrder("USB cable", 20);
        System.out.println("main returns now, so the program ends");    }}
Output
Running on: main
Alive: true
main takes order: Keyboard
main prints bill: Keyboard, Rs 60
main takes order: USB cable
main prints bill: USB cable, Rs 20
main returns now, so the program ends

What this code does

  • takeOrder and printBill both print main: calling a method moves deeper into the same thread's call stack, it does not start a new thread.
  • isAlive() is true because the thread is still running. Once main returns and no other threads are running, the program ends.

Calling a method never creates a thread: the called method runs on the same thread as the caller. Thread.currentThread() returns the thread running the current line, and getName() gives its name. The crash message Exception in thread "main" names this thread: the exception was not caught and ended it. The JVM also runs helper threads of its own, such as the garbage collector, in the background.

Next step

Check your understanding

12 quick questions