Threads vs.
Processes
Understand how operating systems manage execution units and how Java threads share memory within a single process.
What is a Process?
A process is an independent program in execution. Every time you launch an application: a web browser, a game, or a Java program: the operating system creates a new process for it.
What is a Thread?
A thread is the smallest unit of execution within a process. Think of it as a lightweight sub-task that runs inside the process's shared memory space.
Why Does This Matter?
Modern applications need to do many things at once: respond to user input, fetch data from the network, and render graphics. Understanding threads and processes is the foundation of concurrent programming in Java.
Process Memory Model
Thread Memory Model
The Core Rule
Key Distinction: Isolation vs. Sharing
| Process | Thread | |
|---|---|---|
| Memory | Separate address space | Shared heap within process |
| Creation Cost | Heavy: OS allocates full context | Light: only stack + PC |
| Communication | IPC (sockets, pipes, files) | Shared variables (fast) |
| Crash Impact | Only that process dies | Can crash entire process |
| Example | Chrome tabs (separate PIDs) | Java's Thread class |
How to Apply This Knowledge
Example 1: Creating a Thread
Example 2: Threads Sharing Data
Example 3: Visualizing the Difference
Thread Lifecycle
Launching a Process from Java
Common Mistakes
Summary Comparison
| Feature | Process | Thread |
|---|---|---|
| Address Space | Own (isolated) | Shared with process |
| Creation Speed | Slow (heavy) | Fast (lightweight) |
| Communication | IPC: sockets, pipes | Shared variables |
| Failure Impact | Isolated crash | Can crash whole process |
| Java API | ProcessBuilder | Thread, Runnable |
| Use When | Isolation, security | Parallelism, responsiveness |
Question 1 of 5
Which of the following is true about threads within the same process?
Question 2 of 5
What happens when you call run() directly on a Thread object instead of start()?
Question 3 of 5
A Java application spawns a child process using ProcessBuilder. If the child process crashes, what happens to the parent Java application?
Question 4 of 5
Two threads simultaneously increment a shared static int counter variable 1000 times each without synchronization. What is the most likely outcome?
Question 5 of 5
Which scenario is best suited for using multiple threads rather than multiple processes?