Java · Module 11 · Lesson 11 min read

Threads & Synchronization

Process vs thread

  • A process is a running program with its own memory.
  • A thread is a path of execution inside a process. Threads share the same memory, which makes them fast but risky.

Creating threads

Java
// 1. Pass a Runnable (preferred)
Thread t = new Thread(() -> System.out.println("Hi from " + Thread.currentThread().getName()));
t.start();

// 2. Extend Thread
class Worker extends Thread {
    public void run() { System.out.println("Working…"); }
}
new Worker().start();

⚠️ Call start(), not run(). run() just executes on the current thread.

Thread lifecycle

NEW → RUNNABLE → (BLOCKED / WAITING / TIMED_WAITING) → TERMINATED

  • Thread.sleep(ms) pauses the current thread.
  • t.join() waits for thread t to finish.

The danger: race conditions 🏎️

count++ is really three steps: read, add, write. Two threads can read the same value and one update gets lost.

Fix 1: synchronized

Only one thread at a time can run a synchronized block on the same lock:

Java
synchronized void increment() { count++; }
// or
synchronized (lock) { count++; }

Fix 2: atomic classes

AtomicInteger counter = new AtomicInteger(); counter.incrementAndGet(); → thread-safe without locks.

volatile

Makes changes to a variable visible to all threads immediately (good for flags like running = false). It does not make count++ safe.

Deadlock 💀

Thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1. Both wait forever. ✅ Avoid it by always taking locks in the same order.

Example

Java
public class Counter {
    private int count = 0;

    private synchronized void increment() { count++; }

    public static void main(String[] args) throws InterruptedException {
        Counter c = new Counter();
        Runnable task = () -> {
            for (int i = 0; i < 10_000; i++) c.increment();
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start(); t2.start();
        t1.join();  t2.join();          // wait for both

        System.out.println(c.count);    // always 20000 ✅
        // Remove "synchronized" and you'll often get less!
    }
}