Multithreading
Thread Basics
- Multithreading allows concurrent execution of multiple parts of a program
- Each thread represents an independent path of execution
- Threads share the same memory space and resources
Thread Lifecycle
- New: Thread is created but not yet started
- Runnable: Thread is ready for execution and scheduled
- Running: Thread is currently executing
- Blocked/Waiting: Thread is temporarily inactive (waiting for I/O or another thread)
- Terminated: Thread has completed its execution
Creating Threads
Using Thread Class
class MyThread extends Thread {
public void run() {
// Code to be executed in thread
}
}
// Usage
MyThread thread = new MyThread();
thread.start(); Using Runnable Interface
class MyRunnable implements Runnable {
public void run() {
// Code to be executed in thread
}
}
// Usage
Thread thread = new Thread(new MyRunnable());
thread.start(); Thread Methods
start()- Begins thread executionsleep(long millis)- Pauses thread for specified millisecondsjoin()- Waits for thread to dieyield()- Suggests thread to pause and let others execute
Thread Synchronization
- Prevents multiple threads from accessing shared resources simultaneously
-
Example using
synchronizedkeyword:synchronized void method() { // Only one thread can execute this at a time } // OR synchronized(object) { // Synchronized block } -
Example using
Locks:import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class Counter { private Lock lock = new ReentrantLock(); private int count = 0; void increment() { lock.lock(); try { count++; } finally { lock.unlock(); } } }
3, Example using wait() and notify():
class SharedResource {
synchronized void consume() {
while (/* condition */) {
wait();
}
// Consume resource
notify();
}
synchronized void produce() {
// Produce resource
notify();
}
} Thread Pool
- Manages and reuses threads
- Improves performance by reducing thread creation overhead
- Example
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(new Task()); Common Issues
Deadlock
-
Deadlock occurs when two or more threads are blocked forever, waiting for each other
-
Prevention:
- Lock ordering
- Timeout mechanisms
- Deadlock detection
-
Example:
class DeadlockExample { private Object lock1 = new Object(); private Object lock2 = new Object(); void method1() { synchronized(lock1) { synchronized(lock2) { // Method code } } } void method2() { synchronized(lock2) { synchronized(lock1) { // Method code } } } } -
For another example, see this code (
DeadlockExample.java, below)DeadlockExample.javaclass DeadlockExample { private Object lock1 = new Object(); private Object lock2 = new Object(); void method1() { System.out.println("Thread 1: Attempting to acquire lock1"); synchronized(lock1) { System.out.println("Thread 1: Acquired lock1"); try { Thread.sleep(100); // Delay to ensure deadlock } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread 1: Attempting to acquire lock2"); synchronized(lock2) { System.out.println("Thread 1: Acquired lock2"); } } } void method2() { System.out.println("Thread 2: Attempting to acquire lock2"); synchronized(lock2) { System.out.println("Thread 2: Acquired lock2"); try { Thread.sleep(100); // Delay to ensure deadlock } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread 2: Attempting to acquire lock1"); synchronized(lock1) { System.out.println("Thread 2: Acquired lock1"); } } } public static void main(String[] args) { final DeadlockExample deadlock = new DeadlockExample(); // Create and start first thread Thread thread1 = new Thread(() -> { deadlock.method1(); }); // Create and start second thread Thread thread2 = new Thread(() -> { deadlock.method2(); }); thread1.start(); thread2.start(); } }This program never ends: the two threads wait for each other forever, which would freeze your browser tab. Run it on your computer with
java DeadlockExample.java.Java 21
Race Conditions
-
Race conditions occur when multiple threads access shared resources simultaneously
-
Prevention:
- Synchronization
- Atomic operations
- Thread-safe collections
-
Example:
class UnsafeCounter { private int count = 0; // This method is not thread-safe void increment() { count++; // This is not an atomic operation } }
Thread Safety
Strategies of achieving thread safety:
-
Synchronization
class ThreadSafeCounter { private volatile int count = 0; synchronized void increment() { count++; } } -
Using Atomic Classes
import java.util.concurrent.atomic.AtomicInteger; class ThreadSafeCounter { private AtomicInteger count = new AtomicInteger(0); void increment() { count.incrementAndGet(); } } -
Using Thread-Safe Collections
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();