Notes › Java
Multithreading in Java
A thread is a lightweight path of execution inside a process. Multiple threads let a program do several things at once — handle many web requests, keep a UI responsive while downloading, or use all CPU cores. (Background: Process vs Thread.)
Creating a thread
// 1) implement Runnable (preferred: your class can still extend something else)
class Task implements Runnable {
public void run() { System.out.println("Running in " + Thread.currentThread().getName()); }
}
new Thread(new Task()).start();
// 2) lambda
Thread t = new Thread(() -> System.out.println("Hello from a thread"));
t.start(); // start() creates a new thread; calling run() directly would NOT
t.join(); // wait for t to finish
// 3) extend Thread (less flexible)
class MyThread extends Thread { public void run() { /* ... */ } }
Thread life cycle
NEW → RUNNABLE → (BLOCKED / WAITING / TIMED_WAITING) → RUNNABLE → TERMINATED
sleep(ms)→ TIMED_WAITING (keeps locks)wait()→ WAITING (releases the lock)- waiting for a
synchronizedlock → BLOCKED
Race condition
class Counter {
int count = 0;
void increment() { count++; } // read → add → write: NOT atomic
}
Two threads incrementing 1,000 times each may end with less than 2,000 because their read-add-write steps interleave.
synchronized
Only one thread at a time can run a synchronized block on the same lock.
class Counter {
private int count = 0;
synchronized void increment() { count++; } // lock = this object
void add(int x) {
synchronized (this) { count += x; } // synchronized block
}
}
Static synchronized methods lock the class object.
Other tools
| Tool | Use |
|---|---|
AtomicInteger |
lock-free counters: count.incrementAndGet() |
volatile |
every read sees the latest write (visibility), but not atomic for ++ |
ReentrantLock |
like synchronized, plus tryLock(), timeouts, fairness |
ConcurrentHashMap |
thread-safe map without locking the whole map |
CountDownLatch, Semaphore |
wait for N tasks / limit concurrent access |
wait / notify (producer–consumer)
synchronized void put(int x) throws InterruptedException {
while (queue.size() == CAP) wait(); // always wait in a while loop
queue.add(x);
notifyAll();
}
synchronized int take() throws InterruptedException {
while (queue.isEmpty()) wait();
int x = queue.remove();
notifyAll();
return x;
}
In real code, use a BlockingQueue (e.g. ArrayBlockingQueue) instead.
ExecutorService (thread pools)
Creating a thread per task is expensive. A pool reuses a fixed number of threads.
ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> f = pool.submit(() -> 2 + 3); // Callable returns a value
System.out.println(f.get()); // 5 (waits for the result)
pool.shutdown();
CompletableFuture chains async steps: supplyAsync(...).thenApply(...).thenAccept(...).
Deadlock
Thread A holds lock 1 and waits for lock 2; thread B holds lock 2 and waits for lock 1 — both wait forever.
Avoid it: always take locks in the same order, hold locks briefly, use tryLock with a timeout. See Deadlocks.
Interview one-liners
start()vsrun():start()creates a new thread;run()is just a normal method call.sleep()keeps the lock;wait()releases it and must be called insidesynchronized.volatilegives visibility, not atomicity.- Prefer
Runnable/Callable+ExecutorServiceover extendingThread. Thread.yield()is only a hint to the scheduler.