Multithreading (Doing Multiple Tasks at Once)
Discover how Java runs multiple tasks concurrently using threads, thread lifecycle states, locking critical sections with synchronized, and inter-thread signaling.
Imagine trying to cook dinner where you have to wait for the water to boil completely before you even start chopping vegetables! That would take forever. Multithreading lets Java perform multiple tasks simultaneously.
6.1. 1. What is Multithreading & How to Create Threads
Definition: A Thread is an independent path of execution inside a program that runs concurrently alongside other threads.
Core Working Principles:
- Multitasking: Allows your application to perform background tasks (like downloading a file) while keeping the user interface responsive.
- Two Ways to Create Threads:
- 1. Extend the
Threadclass and overriderun(). - 2. Implement the
Runnableinterface and pass it tonew Thread(runnable).start()(Preferred!).
• Single-Threaded: One chef doing everything sequentially—boiling water, cutting onions, baking bread one by one.
• Multithreaded: Three chefs working concurrently at different stations! Chef 1 boils water, Chef 2 cuts onions, Chef 3 bakes bread simultaneously!
5-Marks Exam Scoring Points
- Multithreading runs multiple tasks concurrently within one application.
- Implementing Runnable is preferred over extending Thread for inheritance flexibility.
- Always call thread.start() to launch a new execution thread.
6.2. 2. The 6 Thread Lifecycle States
Definition: A Java thread passes through 6 distinct stages from birth to termination.
Core Working Principles:
- 1. NEW: Created thread object before calling
start(). - 2. RUNNABLE: Currently executing or ready to run on the CPU.
- 3. BLOCKED: Waiting to acquire a lock held by another thread.
- 4. WAITING: Paused indefinitely waiting for a signal.
- 5. TIMED_WAITING: Sleeping for a specific duration e.g.
Thread.sleep(1000). - 6. TERMINATED: Finished executing its task.
graph TD
New[1. NEW] -->|start| Runnable[2. RUNNABLE]
Runnable -->|sleep| TimedWait[3. TIMED_WAITING]
Runnable -->|wait| Waiting[4. WAITING]
Runnable -->|lock blocked| Blocked[5. BLOCKED]
Runnable -->|task completed| Terminated[6. TERMINATED]
5-Marks Exam Scoring Points
- Threads move through 6 states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED.
- Thread.sleep() pauses execution without losing monitor locks.
- Calling start() twice on the same thread throws an exception.
6.3. 3. Preventing Collisions: Synchronization & Signaling
Definition: Synchronization prevents two threads from editing the exact same variable at the exact same time using locks.
Core Working Principles:
- Race Condition: When two threads try to update shared data simultaneously, causing corrupted or incorrect numbers.
- The
synchronizedKeyword: Locks a method or block so only ONE thread can enter at a time. - Signaling (
wait()¬ify()): Allows threads to notify each other when work is ready.
The synchronized keyword acts like a lock on a single-occupancy bathroom door:
• When Thread A enters, it locks the door.
• If Thread B arrives, it must wait outside in line until Thread A finishes and unlocks the door!
5-Marks Exam Scoring Points
- synchronized prevents race conditions by locking shared critical sections.
- Only one thread can hold a synchronized lock at any given moment.
- wait() releases the lock; notify() wakes up a waiting thread.
✍️ Chapter 6 Reference Exercises & Review Problems
- Calling `thread.start()` instructs the JVM to spawn a **brand new independent thread stack** on the CPU.
- Calling `thread.run()` directly just executes the code on the main existing thread without spawning a new concurrent thread!
When multiple threads access a shared variable (like a bank account balance), if two threads edit it at the same microsecond, data corruption occurs. The `synchronized` keyword locks the method so only ONE thread can enter at a time, keeping data safe!