JAVA MULTITHREADING – LONG ANSWERS & DIAGRAMS
1. CREATING THREADS
Threads in Java are lightweight subprocesses that allow concurrent execution. Java provides two
ways to create threads:
(a) Extending Thread class
(b) Implementing Runnable interface
Thread creation is used to perform multiple tasks simultaneously, improving performance and
responsiveness in applications.
2. THREAD PRIORITY
Each thread has a priority used by the thread scheduler to decide execution order. Priority ranges
from 1–10:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Higher priority threads get more CPU time but scheduling is not guaranteed.
3. BLOCKED STATES (THREAD LIFE CYCLE)
A thread in Java passes through different states:
NEW → RUNNABLE → RUNNING → BLOCKED/WAITING → TERMINATED.
Diagram:
NEW → START() → RUNNABLE → RUNNING → (WAITING / BLOCKED / TIMED WAITING) →
TERMINATED
4. EXTENDING THREAD CLASS
Thread class is extended and run() method is overridden. start() begins parallel execution. Useful
when you directly need thread capabilities.
5. RUNNABLE INTERFACE
Runnable is preferred because it allows multiple inheritance and better design. A Thread object
executes the run() method of Runnable.
6. STARTING THREADS
Calling start() allocates separate call stack and invokes run() internally. Directly calling run() will
NOT create a new thread.
7. THREAD SYNCHRONIZATION
Synchronization ensures one thread accesses critical section at a time. It prevents race conditions
and inconsistent data.
8. SYNCHRONIZED CODE BLOCK
Instead of synchronizing an entire method, only the critical part is synchronized using:
synchronized(object) { ... }
9. OVERRIDING SYNCHRONIZED METHODS
Synchronized methods can be overridden but lock belongs to the object, not the method. Careful
design is needed.
10. THREAD COMMUNICATION (INTER-THREAD COMMUNICATION)
Threads cooperate using wait(), notify() and notifyAll() in producer–consumer style problems. Must
be used inside synchronized blocks.
11. WAIT(), NOTIFY(), NOTIFYALL()
wait() – releases lock and waits
notify() – wakes one waiting thread
notifyAll() – wakes all waiting threads
Flow Diagram:
Thread enters synchronized block → calls wait() → releases lock → another thread calls notify() →
waiting thread resumes.