Multi Threading
Multi Threading
Java
Multithreading is a powerful feature in Java that allows developers to create
applications that can perform multiple tasks concurrently. This can lead to increased
efficiency, responsiveness, and overall performance of your application.
by RACHAMALLA RUCHITHA
What is a Thread?
1 Fundamental Unit of 2 Independent Path of
Execution Execution
A thread is the smallest unit of Each thread has its own stack,
execution within a process. It program counter, and registers,
allows a program to perform allowing it to execute
multiple tasks simultaneously. independently from other
threads.
3 Shares Resources
Threads within the same process share resources like memory and CPU,
which enables efficient communication and data sharing.
Thread Creation
Extending Thread Class Implementing Runnable Thread Pools
Interface
Create a new class that extends the Thread Use a thread pool to manage and reuse a
class and override the run() method. Create a class that implements the Runnable pool of pre-created threads, improving
interface and pass an instance of it to a new performance and scalability.
Thread object.
Thread Synchronization
Synchronized Methods Synchronized Blocks
Use synchronized blocks to protect
Ensure that only one thread can critical sections of code that access
execute a synchronized method at shared resources.
a time, preventing race conditions.
wait() notify()
Allows a thread to temporarily release Wakes up a single thread waiting on the
the lock and suspend its execution until object's monitor.
notified.
notifyAll() join()
Wakes up all threads waiting on the Waits for a thread to terminate before
object's monitor. the current thread continues.
Thread Deadlocks and Starvation
Deadlocks
Occurs when two or more threads are blocked, each holding a resource that another thread is
waiting for.
Deadlock Avoidance
Carefully design your code to avoid deadlocks by following best practices like acquiring
locks in a consistent order.
Starvation
Occurs when a thread is never given the opportunity to access a shared resource, leading to
unfairness.
Starvation Mitigation
Use fair locking mechanisms and prioritize threads based on their importance to prevent
starvation.
Conclusion and Best Practices
Use Thread Pools Manage and reuse a pool of pre-created
threads to improve performance and
scalability.