Sub topic 1
What Is a Thread and Why Use More Than One?
Every Java program you have written so far did one thing at a time. It ran the first line, then the second, then the third, until it reached the end. This chapter explains the idea that lets a program do more than one thing at once. That idea is the thread.
You will not create your own threads yet. That comes in the next chapter. Here you will build the mental model that the rest of the tutorial uses.
Programs, Processes, and Threads
Three words come up again and again, so let's define them first.
- A program is the code you wrote, stored in files. A compiled Java program is a set of
.classfiles. It does nothing until you run it. - A process is a running program. When you type
java MyApp, the operating system starts a process. The operating system is the software that manages your computer, such as Windows, macOS, or Linux. It gives the process its own block of memory and keeps it apart from other processes. - A thread is one path of execution inside a process. It is a worker that runs your code one step at a time. Every process has at least one thread, and many processes have several.
Picture a restaurant kitchen. The kitchen is the process. It has its own space, its own fridge, and its own tools. The cooks are the threads. Each cook follows their own recipe step by step, and all the cooks share the same fridge and the same tools.
That sharing is the most important fact in this tutorial. Threads in the same process share memory. This makes them fast to work with, and it also makes them easy to get wrong.
What threads share and what they keep to themselves
Each thread has a stack, a private area of memory that holds the local variables and method calls that this thread is running right now. One thread cannot see another thread's local variables.
All threads in a process share the heap, the area of memory where Java stores objects. If two threads hold a reference to the same object, both of them can read it and change it.
Process versus thread at a glance
| Feature | Process | Thread |
|---|---|---|
| What it is | A running program | One path of execution inside a process |
| Memory | Its own, kept apart from other processes | Shares the heap with other threads in the same process |
| Private data | Its whole memory space | Its own stack (local variables, method calls) |
| Cost to start | Higher: the operating system sets up new memory | Lower: it reuses the process's memory |
| Talking to others | Needs special tools such as files, pipes, or network sockets | Can read and write the same objects directly |
| If it crashes | Other processes keep running | An uncaught error usually stops only that thread, but shared data may be left half-changed |
The Main Thread
When you run a Java program, the JVM starts. The JVM (Java Virtual Machine) is the program that runs your compiled Java code. It creates a thread named main and uses it to call your main method. Every line you have ever written in main ran on this thread.
The JVM also starts a few helper threads of its own in the background, for example one for garbage collection. Garbage collection is the JVM's automatic cleanup of objects you no longer use. You do not control those threads, but they show that even a "simple" Java program has more than one thread.
You can ask Java which thread is running your code right now. Thread.currentThread() returns the current thread, and getName() returns its name. The program below also asks how many processor cores your computer has. A core is a part of the processor that can run one thread's instructions at a time.
public class WhoAmI {
public static void main(String[] args) {
Thread current = Thread.currentThread();
System.out.println("Running on thread: " + current.getName());
int cores = Runtime.getRuntime().availableProcessors();
System.out.println("This machine has " + cores + " cores available to Java");
}
}Save it as WhoAmI.java, then compile and run it:
javac WhoAmI.java
java WhoAmIThe output looks like this, and the number of cores depends on your machine:
Running on thread: main
This machine has 8 cores available to JavaWhy Use More Than One Thread?
If one thread can run your whole program, why add more? There are two main reasons.
Reason 1: Waiting without wasting time
A lot of real programs spend most of their time waiting. They wait for a file to load, for a web server to reply, or for a database to answer a query. While one thread waits, it does nothing useful.
With several threads, one thread can wait while another keeps working. This is called concurrency: making progress on several tasks during the same period of time. The tasks take turns, so none of them blocks the others.
The program below runs on one thread. It pretends to download two files, and each download takes one second. Thread.sleep pauses the current thread for a number of milliseconds, which stands in for the waiting. It can throw a checked exception called InterruptedException, so main declares it with throws. A later chapter explains that exception.
public class SlowDownloads {
static void download(String file) throws InterruptedException {
System.out.println("Start " + file);
Thread.sleep(1000); // pretend the network takes 1 second
System.out.println("Done " + file);
}
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
download("photo.jpg");
download("report.pdf");
long elapsed = System.currentTimeMillis() - start;
System.out.println("Total time: " + elapsed + " ms");
}
}The output looks like this:
Start photo.jpg
Done photo.jpg
Start report.pdf
Done report.pdf
Total time: 2005 msThe total is about two seconds, because the second download cannot start until the first one finishes. If each download had its own thread, both waits would happen at the same time, and the total would drop to about one second. You will make that change yourself in the next chapter.
Reason 2: Using every core
Modern computers have several cores. A program with one thread can only use one core at a time, even if seven others sit idle.
If you split heavy calculation work across several threads, the operating system can run them on different cores at the very same moment. This is called parallelism: truly running several things at the same instant.
| Term | Meaning | Needs more than one core? | Typical example |
|---|---|---|---|
| Concurrency | Several tasks make progress during the same period, possibly by taking turns | No | A server handling many users who are each waiting on the network |
| Parallelism | Several tasks run at the exact same instant | Yes | Resizing thousands of photos using all cores |
A third reason: keeping programs responsive
Desktop and mobile apps often have one thread that draws the screen and reacts to clicks. If that thread starts a long job, the window freezes. Moving the long job to another thread keeps the screen responsive. Servers use the same idea: each incoming request can be handled without making other users wait.
Who Decides Which Thread Runs?
You might have more threads than cores, for example 50 threads on an 8-core machine. The operating system's scheduler decides which threads run on which cores, and for how long. It switches between threads very quickly, often many times per second. To a person it looks as if all 50 run at once.
You do not control the scheduler, and you cannot predict the exact order in which it runs threads. If you run the same multi-threaded program twice, the output lines may come out in a different order each time. This is normal.
The Cost of More Threads
Threads are useful, but they come with costs.
- Memory. Each classic Java thread reserves memory for its stack, often around 1 MB by default. Thousands of threads use a lot of memory.
- Switching. When the scheduler swaps one thread for another, it spends a little time saving and restoring state. Too many threads means more time spent switching and less time spent working.
- Shared data bugs. Two threads that change the same object at the same moment can corrupt it. This is called a race condition, and it gets a chapter of its own.
- Harder debugging. Because the order changes from run to run, a bug may appear once in a hundred runs.
This is why the later half of the tutorial moves from creating threads by hand to the ExecutorService. An ExecutorService is a Java tool that keeps a small, reusable group of threads, called a thread pool, and hands tasks to them. It limits how many threads exist and handles a lot of the bookkeeping for you.
Summary
- A process is a running program with its own memory. A thread is one path of execution inside it.
- Threads in one process share the heap but each has its own stack.
- Java starts your code on a thread named
main. - Multiple threads let a program overlap waiting (concurrency), use several cores (parallelism), and stay responsive.
- The scheduler picks which thread runs, so the order is unpredictable.
- Threads cost memory and add the risk of race conditions, which later chapters teach you to control.
Exercise
Two threads run inside the same Java process. Thread A creates a local variable int count = 5; inside a method. Thread B has a reference to the same ArrayList object as Thread A. Which of these can Thread B see or change: the variable count, the ArrayList, or both? Explain why.
Show answer
Thread B can see and change only the ArrayList. The local variable count lives on Thread A's private stack, which no other thread can access. The ArrayList is an object, so it lives on the shared heap, and any thread that holds a reference to it can read or modify it.
Exercise
A program reads 100 web pages, and each request spends about 2 seconds waiting for the server and almost no time on the CPU. The machine has 4 cores. Would adding threads mostly help through concurrency or through parallelism? About how long does the work take on one thread?
Show answer
It helps mostly through concurrency. The threads spend their time waiting, not computing, so overlapping the waits is what saves time, and that works even on a single core. On one thread the work takes about 100 × 2 = 200 seconds. With many threads waiting at once, it could finish in a few seconds.
Exercise
Run the WhoAmI program, then change SlowDownloads so it downloads three files instead of two. Predict the total time before you run it, then check your prediction.
Show answer
Add a third call such as download("video.mp4"); in main. Each call sleeps for 1000 ms on the same main thread, one after another, so the total is about 3000 ms (usually a few milliseconds more). WhoAmI prints "main" as the thread name and the number of cores your machine reports.