Chapter One: Multithreading
1.1 Introduction
Multithreading allows multiple threads (lightweight sub-processes) to execute concurrently for
maximum CPU utilization. It improves performance, responsiveness, and resource sharing. Typical
applications include web servers, games, and editors that handle background tasks simultaneously.
1.2 Thread States: Life Cycle of a Thread
Threads move through five main states: New, Runnable, Running, Blocked/Waiting, and
Terminated. - New: Thread created but not started. - Runnable: Thread ready to run after calling
start(). - Running: Thread executing run() method. - Blocked/Waiting: Thread waiting for resources
or signal. - Terminated: Thread execution completed or stopped.
1.3 Thread Priority and Scheduling
Threads have priorities from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY). The scheduler allocates
CPU based on priority or time-slicing.
1.4 Creating and Executing Threads
Threads can be created by: 1. Extending the Thread class and overriding run(). 2. Implementing
Runnable interface and passing instance to Thread object.
1.5 Thread Synchronization
Synchronization prevents data corruption when multiple threads access shared resources. The
synchronized keyword ensures one thread executes a critical section at a time.
1.6 Producer/Consumer without Synchronization
Without synchronization, producer and consumer threads may interfere, leading to inconsistent
data or lost updates.
1.7 Producer/Consumer with Synchronization
Using synchronized methods and wait()/notify() ensures proper coordination between producer and
consumer threads, maintaining data integrity.
1.8 Circular Buffer
A circular buffer allows continuous data production and consumption. When the buffer is full,
producer waits; when empty, consumer waits.
1.9 Daemon Threads
Daemon threads run in the background (e.g., garbage collector). They end automatically when all
user threads finish execution.
1.10 Runnable Interface
Runnable defines the run() method for thread tasks. It allows better separation between task logic
and thread control, supporting multiple inheritance.
Summary
Threads enable concurrent execution. Synchronization ensures consistency, and daemon threads
support background services. Runnable interface is preferred for flexibility.