Process and thread
What you'll learn:
- tell a process from a thread and name what the threads of one program share;
- start a thread with
start(), wait for it withjoin()and never confusestart()withrun(); - explain why
count++from two threads loses increments; - protect a shared counter with
synchronizedandAtomicInteger.
Picture a restaurant kitchen. Several cooks work in it: one makes soup, another cuts salad, a third fries cutlets. The work goes on at the same time, and nobody waits for another cook to finish a dish.
The cooks have things they share and things of their own. They share the fridge with the food and the board on the wall where they mark how many dishes went out. Each has their own notepad to count in and their own place in the recipe they have reached. The restaurant next door stands in a separate building with its own kitchen, and our cooks never look into its fridge.
Why does a programmer need this? Almost any serious program does several things at once. A server answers thousands of users, a game draws a frame while it loads a level. Java has threads for this, and in this theme the kitchen is a program and the cooks are its threads.
What "at the same time" means
A processor runs a program's instructions. It has several cores, and each core runs one sequence of instructions at a time:
- on four cores, four threads truly run at the same time;
- there are usually far more threads than cores, so the operating system switches a core from one thread to another many times a second;
- from the outside it looks as if they all run at once.
The operating system decides who gets a core and when. That is why the order in which threads run is not fixed and changes from run to run.
Process
A process is a running program with its own memory. A browser, a music player and your Java program are three different processes. The operating system keeps their memory apart: one process cannot read another's variables.
The command java Main.java starts one process, the JVM, which runs your program. In our picture, a process is the whole kitchen with its fridge and board, and the restaurant next door is another process.
Thread
A thread is a sequence of instructions that runs inside a process. It is a cook in the kitchen: they follow their own recipe line by line. Many threads can work in one process, and they all use that process's memory.
What threads share
- Objects in the heap, everything created with
new. If two threads hold a reference to one object, they work with the very same object. staticfields. They belong to the class, and a program has one copy of each class.
These are the fridge and the board on the wall: every cook sees them.
What each thread has of its own
- Local variables and method parameters. If two threads run the same method, each gets its own copy of its variables.
- Its place in the program, the line the thread is running now.
These are the cook's notepad and their place in the recipe.
How a process differs from a thread
Interviewers like to ask this. The answer has three parts:
- a process is a separate program with its own memory, while a thread runs inside a process;
- the threads of one process share the heap and
staticfields, while each thread has its own local variables; - a thread is cheaper than a process: it needs no separate memory space of its own, so it is faster to create and to switch to.
Here the kitchen picture is inaccurate. Cooks see each other and can agree on who goes to the board first. Threads do not see each other: two threads can take hold of one object at the same instant, and Java will not stop them.
The main thread
Even in a program where you created no threads, there is one thread. The JVM runs main in a thread that is called exactly that, main. Let's check:
public class Main {
public static void main(String[] args) {
String name = Thread.currentThread().getName();
System.out.println(name); // main
}
}Let's go through it step by step:
Threadis a class from the standard library: every thread in Java is represented by an object of this class.Thread.currentThread()is astaticmethod that returns the object of the thread running this line.getName()returns the thread's name, and the program printsmain.
You have already met this name in the line Exception in thread "main": that is how the JVM reports that the exception happened in the main thread. Besides main, the JVM starts several service threads for its own work, so even the shortest Java program is multithreaded.
Common mistake
The thread's name was asked of the class Thread itself:
String name = Thread.getName(); // ✗error: non-static method getName() cannot be referenced from a static contextThe program does not compile. getName() is a method of an object, not of the class: each thread has its own name, and the compiler needs to know whose. First get the thread object with Thread.currentThread(), then ask it for its name: Thread.currentThread().getName().
Key points
- A process is a running program with its own memory, and a thread is a sequence of instructions inside a process.
- The threads of one process share objects in the heap and
staticfields, while each thread has its own local variables. - The operating system decides the order in which threads run, and it differs from run to run.
mainruns in the main thread namedmain, andThread.currentThread()returns the thread running the current line.