Jan 24, 2026
## Chapter 18: Multithreading (The "Multi-Worker" Kitchen)
Normally, Java runs your code line-by-line, like one person doing all the chores. Multithreading is like hiring more workers.
### 1. Starting a Worker
**Example 1: The Background Task (Basic)**
```java
Thread t = new Thread(() -> {
System.out.println("I'm doing heavy work in the background...");
});
t.start(); // The worker starts
System.out.println("I'm the main thread, I'm not waiting!");
```
### 2. Common Student Mistake: The "Race Condition"
**Example 2: Two people, one notebook**
```java
class Counter {
int count = 0;
void add() { count++; } // DANGEROUS!
}
```
*Teacher's Note:* If two threads call `add()` at the exact same time, they might both read `count` as 5, add 1, and write 6. One update is lost! This is why your bank balance or game score might glitch if not handled correctly.
### 3. The Solution: Synchronized
**Example 3: The Bathroom Lock (Explanation)**
```java
class SafeCounter {
private int count = 0;
public synchronized void add() { count++; } // SAFE
}
```
*Teacher's Note:* `synchronized` is like a bathroom lock. Only one thread can enter the method at a time. Others have to wait in line.
### 4. Real-Life Example
**Example 4: A Loading Screen**
While a big game file downloads on one thread, another thread keeps the "Loading..." animation spinning so the user doesn't think the app crashed.
### 5. Future Hint
**Example 5: ExecutorService (Future Hint)**
Creating 1000 threads manually will crash your computer. In professional work, we use a "Thread Pool" (ExecutorService). It's like a staffing agency that manages workers for you.