Topic 15 of 30 · Advanced
Multithreading Basics
Threads, synchronization, volatile and race conditions.
Concept
A thread is an independent path of execution. Create one with Runnable/Thread, or better, submit tasks to an ExecutorService.
When threads share mutable data, race conditions occur. synchronized blocks give mutual exclusion and visibility; volatile gives visibility only.
Deadlock: threads wait forever on each other's locks. Avoid by locking in a consistent order and using timeouts.
Code (Java 21)
class Counter {
private int count = 0;
synchronized void inc() { count++; } // count++ is not atomic otherwise
int get() { return count; }
}
Counter c = new Counter();
Runnable task = () -> { for (int i = 0; i < 1000; i++) c.inc(); };
Thread t1 = new Thread(task), t2 = new Thread(task);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(c.get()); // 2000Remember
- start() creates a thread; run() just calls a method.
- count++ is read-modify-write — not atomic.
- volatile ≠ atomic.
Interview questions
start() vs run()?
start() creates a new thread which calls run(). Calling run() directly runs it on the current thread.
wait() vs sleep()?
wait() releases the monitor and waits for notify; must be in synchronized. sleep() pauses without releasing locks.
Lesson test
Take an 8-question test on “Multithreading Basics” — concepts, output prediction, bug spotting and interview questions.