Multithreading in Java allows multiple threads to run concurrently, making applications more responsive, scalable, and efficient — especially for tasks like I/O handling, background processing, and real-time updates.
This guide walks you through the basics of Java multithreading and how to use it effectively.
1. What Is a Thread?
A thread is the smallest unit of execution within a process. Java enables multithreading by allowing multiple threads to run within the same JVM, sharing memory and CPU time.
2. Creating Threads in Java
Option 1: Extend the Thread class
java
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
new MyThread().start();
Option 2: Implement the Runnable interface
java
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running");
}
}
new Thread(new MyRunnable()).start();
3. Thread Lifecycle
A thread in Java goes through the following states:
- New
- Runnable
- Running
- Blocked/Waiting
- Terminated
You can control it using methods like start(), sleep(), join(), and interrupt().
4. Synchronization and Thread Safety
Java provides the synchronized keyword to prevent race conditions when multiple threads access shared resources:
java
public synchronized void increment() {
counter++;
}
Other thread-safety mechanisms:
ReentrantLockAtomicIntegervolatile keyword
5. Thread Communication with wait() and notify()
java
synchronized(obj) {
obj.wait(); // thread waits
obj.notify(); // wakes a waiting thread
}
Used for coordinating threads, such as producer-consumer problems.
6. Executor Framework and Thread Pools
For better thread management, use the Executor Framework:
java
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> System.out.println("Running task"));
executor.shutdown();
Types of thread pools:
FixedThreadPoolCachedThreadPoolScheduledThreadPool
7. Callable and Future
Use Callable when you want a thread to return a result:
java
Callable<Integer> task = () -> 42;
Future<Integer> result = executor.submit(task);
System.out.println(result.get());
8. Concurrency vs Parallelism
- Concurrency: Multiple tasks appear to run simultaneously (managed by the OS or JVM)
- Parallelism: Tasks actually run at the same time on multiple cores
9. Common Issues in Multithreading
- Race conditions
- Deadlocks
- Starvation
- Livelocks
Avoid them with proper synchronization, lock ordering, and thread-safe classes.
10. Conclusion
Java's multithreading capabilities are powerful but must be used with care. Whether you're handling background tasks or building high-performance systems, understanding thread management, synchronization, and the Executor framework is essential.