Java Notes
Complete introduction to Multithreading in Java — what threads are, processes vs threads, why multithreading matters, concurrency vs parallelism, and how the JVM manages threads.
What is a Thread?
A thread is the smallest unit of execution within a process. It represents a single sequential flow of control — a path of execution through your code.
Think of it this way:
- A process is like a restaurant (independent entity with its own resources)
- A thread is like a waiter in that restaurant (works within the restaurant, shares its resources)
Multiple waiters (threads) can serve customers simultaneously in the same restaurant (process), sharing the kitchen (memory), tables (variables), and menu (code).
Process vs Thread
| Feature | Process | Thread |
|---|---|---|
| Definition | Independent program in execution | Lightweight sub-unit of a process |
| Memory | Own memory space (isolated) | Shares memory with other threads |
| Communication | Inter-process (pipes, sockets) — slow | Direct (shared variables) — fast |
| Creation cost | Heavy (OS allocates new memory) | Light (shares existing memory) |
| Context switch | Expensive | Cheap |
| Crash impact | Doesn't affect other processes | Can crash the entire process |
| Example | Chrome tabs (separate processes) | Multiple downloads in one browser |
Why Multithreading?
1. Responsiveness (UI Applications)
Output (WithThreads):
| UI | Showing login screen |
| UI | Ready for input immediately! |
| UI | User can interact while download happens |
2. Performance (Utilizing Multiple CPU Cores)
Output:
| Available CPU cores | 8 |
| Single-threaded | 85 ms (sum=4999999950000000) |
| Multi-threaded | 15 ms (sum=4999999950000000) |
| Speedup | 5.7x |
3. Resource Utilization
While one thread waits for I/O (disk, network), other threads use the CPU.
4. Simplified Modeling
Some problems naturally decompose into concurrent tasks (web servers handling multiple clients, game loops with physics + rendering + AI).
Concurrency vs Parallelism
CONCURRENCY (single core)
Time →
Thread A: ████░░░░████░░░░████
Thread B: ░░░░████░░░░████░░░░
(Interleaved — APPEARS simultaneous)
PARALLELISM (multi-core)
Time →
Core 1 - Thread A: ████████████████████
Core 2 - Thread B: ████████████████████
(Actually simultaneous)
| Aspect | Concurrency | Parallelism |
|---|---|---|
| Definition | Managing multiple tasks | Executing multiple tasks simultaneously |
| Hardware | Can work on 1 core | Requires multiple cores |
| Goal | Responsiveness, structure | Speed, throughput |
| Analogy | One chef, many dishes (switching) | Many chefs, many dishes (parallel) |
Java threads can provide both — the JVM and OS schedule them across available cores.
The Main Thread
Every Java program starts with one thread — the main thread:
public class MainThread {
public static void main(String[] args) {
// This code runs on the "main" thread
Thread currentThread = Thread.currentThread();
System.out.println("=== Main Thread Info ===");
System.out.println("Name: " + currentThread.getName());
System.out.println("ID: " + currentThread.getId());
System.out.println("Priority: " + currentThread.getPriority());
System.out.println("State: " + currentThread.getState());
System.out.println("Alive: " + currentThread.isAlive());
System.out.println("Daemon: " + currentThread.isDaemon());
System.out.println("Group: " + currentThread.getThreadGroup().getName());
System.out.println("\nActive threads: " + Thread.activeCount());
}
}Output:
| Name | main |
| ID | 1 |
| Priority | 5 |
| State | RUNNABLE |
| Alive | true |
| Daemon | false |
| Group | main |
| Active threads | 1 |
How JVM Manages Threads
What Each Thread Has (Private):
- Stack — local variables, method call history
- Program Counter (PC) — current instruction pointer
- Thread state — NEW, RUNNABLE, BLOCKED, etc.
What All Threads Share:
- Heap memory — all objects
- Method area — loaded classes, static variables
- Open resources — file handles, connections
Your First Multi-threaded Program
Output (interleaved — order may vary!):
| [Main] Program started. Thread | main |
| [Main] Count | 1 |
| [Worker] Count | 1 (Thread: MyWorker) |
| [Main] Count | 2 |
| [Worker] Count | 2 (Thread: MyWorker) |
| [Main] Count | 3 |
| [Main] Count | 4 |
| [Worker] Count | 3 (Thread: MyWorker) |
| [Main] Count | 5 |
| [Worker] Count | 4 (Thread: MyWorker) |
| [Worker] Count | 5 (Thread: MyWorker) |
Key observation: The output is interleaved because both threads run concurrently. The exact order depends on the thread scheduler and is non-deterministic.
Common Challenges of Multithreading
| Challenge | Description |
|---|---|
| Race Condition | Multiple threads modify shared data simultaneously → corrupted results |
| Deadlock | Two threads wait for each other forever → program hangs |
| Starvation | A thread never gets CPU time (others always get priority) |
| Livelock | Threads keep responding to each other but make no progress |
| Memory Visibility | One thread's changes not visible to another thread |
Interview Questions
Q1: What is a thread in Java?
Answer: A thread is the smallest unit of execution within a process. It has its own stack and program counter but shares heap memory with other threads in the same process. Java supports multithreading natively through the Thread class and Runnable interface.
Q2: What is the difference between a process and a thread?
Answer: A process is an independent program with its own memory space. A thread is a lightweight execution unit within a process that shares memory with other threads. Threads are cheaper to create, faster to context-switch, and communicate more easily (shared memory) than processes.
Q3: What is the difference between concurrency and parallelism?
Answer: Concurrency means managing multiple tasks that make progress (possibly on a single core via time-slicing). Parallelism means physically executing multiple tasks at the same instant (requires multiple cores). Java's multithreading provides concurrency; the OS schedules threads for parallelism when multiple cores are available.
Q4: What is the main thread in Java?
Answer: The main thread is the first thread created when a Java program starts. It executes the main() method. It can create child threads. The program terminates when the main thread and all non-daemon threads finish.
Q5: Why is multithreading output non-deterministic?
Answer: The thread scheduler (part of OS/JVM) decides which thread runs and for how long. This scheduling is preemptive and depends on factors like system load, available cores, and thread priorities. You cannot predict the exact interleaving of threads without explicit synchronization.
Q6: What shared resources can cause problems in multithreading?
Answer: Any mutable shared state: instance/static variables, collections, file handles, database connections. When multiple threads read and write shared mutable data without synchronization, race conditions occur, leading to data corruption or inconsistent behavior.
Q8: What is the difference between concurrency and parallelism?
A: Concurrency means multiple tasks making progress within overlapping time periods (may use one CPU, interleaving via context switching). Parallelism means tasks literally executing simultaneously on multiple CPU cores. Concurrency is about structure; parallelism is about execution. A single-core machine can be concurrent but never parallel.
Q9: How many threads can a Java program create?
A: There's no fixed Java-level limit. It depends on: (1) OS limits (ulimit on Linux), (2) available memory (each thread needs ~512KB-1MB for its stack), (3) JVM settings (-Xss for stack size). A typical 8GB system might handle 2000-5000 threads, but performance degrades long before that limit due to context-switching overhead.
Q10: What is the main thread in Java?
A: The main thread is the thread that executes public static void main(String[] args). It's the first thread created by the JVM when a program starts. All other threads (child threads) are spawned from it. The program terminates when all non-daemon threads (including main) finish.
Q11: What are the advantages of multithreading?
A: (1) Better CPU utilization — while one thread waits for I/O, others can run. (2) Responsiveness — UI remains interactive during background operations. (3) Resource sharing — threads share process memory (cheaper than processes). (4) Scalability — can leverage multiple CPU cores. (5) Simplified modeling of concurrent real-world scenarios.
Q12: What are the disadvantages/challenges of multithreading?
A: (1) Race conditions — shared data corruption. (2) Deadlocks — threads waiting for each other forever. (3) Complexity — harder to debug, test, and reason about. (4) Context switching overhead. (5) Memory overhead per thread. (6) Starvation — some threads never get CPU time. (7) Thread safety requires careful synchronization.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Thread Introduction.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, multithreading, thread, introduction
Related Java Master Course Topics