Concurrency · core
Threads, states and wait/notify
A thread has six states. Reading them in a thread dump tells you where a service is stuck. wait and notify coordinate threads, and always need a while loop.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- The six states of
Thread.State: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. - BLOCKED: waiting to enter a
synchronizedblock held by another thread. Many BLOCKED threads on one object mean lock contention. - WAITING:
Object.wait(),join(), or parked byLockSupport.park(ReentrantLock, BlockingQueue.take, Future.get). TIMED_WAITING: sleep, wait or park with a timeout. - RUNNABLE also covers a thread blocked in native I/O such as a socket read: the JVM cannot tell it is waiting.
start()makes a new thread.run()just runs the method on the current thread. Starting a thread twice throws IllegalThreadStateException.waitreleases the monitor and must be called while holding it, or IllegalMonitorStateException is thrown.sleepkeeps every lock it holds.- Use
while, notif, around wait: spurious wakeups, and waking when it is not your turn. - Odd and even printing: a shared lock and counter, or a Semaphore for each thread, or a ReentrantLock with one Condition per thread. The last thread must notify so the other does not wait forever. Producer and consumer:
ArrayBlockingQueue(100): put blocks when full, take blocks when empty. Stop consumers with one poison pill each. On InterruptedException restore the flag. Take dumps withjcmd <pid> Thread.printorjstack <pid>, two or three dumps a few seconds apart.
The red pen
Common traps: mistake → fix
Mistake: run() starts a new thread
Fix: only start() does.
Mistake: sleep releases locks
Fix: sleep keeps them; wait releases the monitor.
Mistake: if (condition) wait() is enough
Fix: use while because of spurious wakeups.
Easy to hard
Questions interviewers ask, easy to hard
- What states can a Java thread be in?
- What is the difference between start and run?
- What is the difference between wait and sleep?
- Write two threads that print odd and even numbers in order.
- Write a producer-consumer with a bounded buffer.
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.