java
- IntroductionInstallation and SetupJava Syntax and StructureRunning Your First ProgramJava VariablesData Types in JavaOperators in JavaJava Input and OutputControl StatementsLoops in JavaMethods in Java (Functions)Arrays in JavaString Handling in JavaOOPS Concept in JavaClasses and ObjectsConstructor and Constructor Overloadingthis KeywordStatic MembersInheritanceAggregation in JavaMethod OverloadingMethod Overridingsuper KeywordFinal Keyword with Class, Method, and VariablesAccess Modifiers in javaEncapsulation in Java Polymorphism in JavaAbstraction in JavaAbstract ClassesInterfaces in JavaDifference between Abstract Class and Interface Nested and Inner Classes Exception HandlingJava PackagesWrapper Classes and AutoboxingJava Collections FrameworkFile Handling in JavaMultithreadingBasics of Java Memory Management and Garbage CollectionJava JDBC
Multithreading in Java – Complete Tutorial
Last Updated on: 26th Nov 2025 16:20:57 PM
Multithreading in Java is a powerful feature that allows a program to execute multiple tasks simultaneously, improving performance, responsiveness, and resource utilization. Each independent task running in parallel is called a thread.
A thread is the smallest unit of execution in a program.
Multithreading is essential in modern applications such as Android apps, servers, games, real-time systems, and large enterprise applications.
Java supports multithreading at the language level using the java.lang.Thread class and the java.lang.Runnable interface.
In real-world applications, systems often need to perform multiple operations at the same time. For example:
-
A web browser loads images, plays videos, handles user input, and downloads files simultaneously.
-
A bank ATM machine reads card input, communicates with the bank server, updates the account, and prints a receipt at the same time.
-
A music player plays songs while showing animations, handling next/previous controls, and downloading album art.
To achieve such parallel tasks smoothly, Java provides Multithreading.
Multithreading improves:
✔ Performance
✔ Efficiency
✔ Faster execution
✔ Better user experience
✔ Less waiting time
✔ Proper CPU utilization
Java uses a Thread Scheduler to decide which thread to run at what time.
Multithreading is a key concept for scalable and responsive applications.
Why Do We Need Multithreading?
❗ Problem Without Multithreading
A single-threaded program can perform only one task at a time.
If one task gets stuck, everything stops.
Example:
If your mobile app is downloading data and it becomes slow, the whole UI freezes.
✔ Solution: Multithreading
Multithreading helps you run multiple tasks together:
-
UI Thread
-
Background Thread
-
Network Thread
-
Database Thread
This prevents application freeze and improves user experience.
Difference Between Process and Thread
| Feature | Process | Thread |
|---|---|---|
| Meaning | Independent program | Smallest part of a process |
| Memory | Separate memory | Shares memory of process |
| Lightweight | No | Yes |
| Communication | Slow | Fast |
| Context Switching | Heavy | Lightweight |
Real Example:
-
Chrome Browser → Process
-
Each Tab inside Chrome → Multiple Threads
How Java Supports Multithreading
Java provides two ways to create a thread:
1. Extending the Thread Class
class MyThread extends Thread {
public void run() {
for(int i=1; i<=5; i++){
System.out.println("Thread Running: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
2. Implementing Runnable Interface
class MyTask implements Runnable {
public void run() {
for(int i=1; i<=5; i++){
System.out.println("Runnable Thread: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyTask());
t.start();
}
}
Thread Lifecycle (States of a Thread)
A thread in Java passes through 5 stages:
-
New – Thread object created
-
Runnable – Ready to run
-
Running – Executing code
-
Blocked/Waiting – Waiting for resource
-
Terminated – Completed
New → Runnable → Running → Blocked/Waiting → Terminated
Important Thread Methods
| Method | Description |
|---|---|
start() |
Starts execution of thread |
run() |
Contains code to execute |
sleep(ms) |
Pauses thread |
join() |
One thread waits for another |
isAlive() |
Checks if thread is running |
yield() |
Gives chance to other threads |
Thread Priorities
Java assigns a priority between 1 to 10.
| Constant | Value |
|---|---|
| MIN_PRIORITY | 1 |
| NORM_PRIORITY | 5 |
| MAX_PRIORITY | 10 |
Higher priority does not guarantee execution, depends on the Thread Scheduler.
Synchronization in Java
When multiple threads access the same resource, data inconsistency occurs. To avoid this, Java provides synchronized keyword.
Example Without Synchronization → Problem
Two customers withdrawing money from the same account at the same time can cause wrong balance.
Example of Synchronized Method
class Bank {
int balance = 1000;
synchronized void withdraw(int amount) {
if(balance >= amount) {
balance -= amount;
System.out.println("Amount Withdrawn: " + amount);
} else {
System.out.println("Insufficient Balance!");
}
}
}
Inter-thread Communication (wait(), notify(), notifyAll())
Used when threads need to communicate with each other.
Example:
-
Producer thread produces items
-
Consumer thread consumes items
Producer waits when buffer is full → wait()
Consumer notifies producer → notify()
Thread Pool (Executor Framework)
Creating too many threads is expensive.
To solve this, Java provides Thread Pools.
ExecutorService service = Executors.newFixedThreadPool(5);
service.execute(new MyTask());
Thread Pool is used in:
-
Servers
-
Web applications
-
Online games
-
Messaging apps
Real-Life Examples of Multithreading
1. Online Food Delivery App
-
Thread 1 → Fetch restaurant list
-
Thread 2 → Track delivery boy live
-
Thread 3 → Handle payment
-
Thread 4 → Chat with support
2. Bank ATM Machine
-
Thread 1 → Read card
-
Thread 2 → Connect to server
-
Thread 3 → Update account
-
Thread 4 → Print receipt
3. YouTube / Video Player
-
Thread 1 → Play video
-
Thread 2 → Load more frames
-
Thread 3 → Download video data
-
Thread 4 → Update UI
4. WhatsApp
-
Thread 1 → Send message
-
Thread 2 → Receive message
-
Thread 3 → Notification thread
-
Thread 4 → Network connection
Advantages of Multithreading
✔ Faster program execution
✔ Full CPU utilization
✔ Responsive applications
✔ Better user experience
✔ Efficient multitasking
✔ Simplifies complex tasks
Disadvantages of Multithreading
✘ Complex debugging
✘ Risk of deadlock
✘ Race conditions without synchronization
✘ High memory usage if threads increase too much
Common Problems in Multithreading
1. Race Condition
Two threads accessing shared data at same time → wrong output.
2. Deadlock
Two threads waiting for each other forever.
3. Starvation
Low priority thread never gets CPU time.
4. Livelock
Threads keep changing state but can't complete work.
Conclusion
Multithreading is one of the strongest features of Java.
It helps in building:
-
High-performance servers
-
Android applications
-
Real-time systems
-
Gaming applications
-
Financial applications
-
Scalable enterprise apps
Understanding threads, synchronization, thread pools, and inter-thread communication is essential for every Java developer.
Keep practicing — you're doing amazing!
Happy Coding! ![]()
.png)