Sub topic 1
What Is a Thread and Why Use More Than One?
Threads and processes
A process is a running program. It has its own memory. A thread is one path of work inside a process. Each process starts with at least one thread. In Java, that first thread is called main.
A process can run many threads at once, and they all share the process's memory. This lets a program do several things at the same time. For example, it can load a file while the screen stays responsive.
Your first thread
A Runnable is an interface that holds a piece of work. It has one method, run. A Thread is the object that runs that work on a new path.
public class HelloThread {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> System.out.println("Hello from " + Thread.currentThread().getName());
Thread worker = new Thread(task, "worker-1");
worker.start();
worker.join();
System.out.println("Main thread done");
}
}Calling start() begins the new thread. If you call run() instead, no new thread starts. The work just runs on main.
Waiting, sleeping, and interrupting
These methods control how threads wait:
| Method | What it does |
|---|---|
| `join()` | Waits until another thread finishes |
| `Thread.sleep(ms)` | Pauses the current thread for a number of milliseconds |
| `interrupt()` | Asks a thread to stop what it is doing |
If a thread is interrupted while it sleeps or waits, it throws an InterruptedException. That is why main above declares throws InterruptedException.
When threads share data: race conditions
Threads share memory, and that can cause trouble. A race condition happens when two threads change the same data at the same time, so the result depends on which thread happens to run first.
The step count++ looks like one step but is really three: read the value, add one, then write it back. If two threads both read the same value, one of the updates is lost.
import java.util.concurrent.atomic.AtomicInteger;
public class CounterDemo {
private static int unsafeCount = 0;
private static final AtomicInteger safeCount = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Runnable work = () -> {
for (int i = 0; i < 100_000; i++) {
unsafeCount++;
safeCount.incrementAndGet();
}
};
Thread a = new Thread(work);
Thread b = new Thread(work);
a.start();
b.start();
a.join();
b.join();
System.out.println("unsafe: " + unsafeCount);
System.out.println("safe: " + safeCount.get());
}
}The unsafe total usually comes out below 200000. The AtomicInteger total is always 200000, because AtomicInteger does the read, add, and write as one step that no other thread can break into.
Exercise
In HelloThread, what changes if you replace worker.start() with worker.run()?
Show answer
No new thread is created. The task runs on the main thread, so it prints "Hello from main" instead of "Hello from worker-1".
Exercise
Why can two threads running unsafeCount++ lose updates?
Show answer
count++ is three steps: read, add, and write. Both threads can read the same old value, and then one thread's write overwrites the other's.