Threads
Threads
1. Basics of Threads
Creating Threads
2. Thread Lifecycle
3. Thread Methods
4. Thread Synchronization
8. Daemon Threads
Background threads that run in the JVM until all user threads finish (e.g., Garbage
Collector thread).
9. Thread Groups
Thread synchronization is a mechanism that ensures that multiple threads do not interfere
with each other when accessing shared resources. Java provides several ways to handle
synchronization:
1. synchronized Keyword
java
CopyEdit
class Counter {
private int count = 0;
java
CopyEdit
class Counter {
private int count = 0;
Example of ReentrantLock
java
CopyEdit
import java.util.concurrent.locks.ReentrantLock;
class SharedResource {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
These methods are used for thread communication inside synchronized blocks or methods.
wait() → Makes the thread wait until another thread calls notify()
notify() → Wakes up a single thread that is waiting
notifyAll() → Wakes up all waiting threads
java
CopyEdit
class SharedQueue {
private int data;
private boolean available = false;
4. volatile Keyword
Ensures that a shared variable's value is always read from the main memory and
not from a thread’s cache.
This guarantees visibility across multiple threads.
java
CopyEdit
class SharedResource {
private boolean running = true;
The running variable might be cached by a thread, leading to an infinite loop even
after stop() is called.
Example with volatile (Correct Behavior)
java
CopyEdit
class SharedResource {
private volatile boolean running = true; // Ensures visibility across
threads
The volatile keyword ensures immediate visibility of changes made by one thread
to all other threads.
Conclusion
Feature Purpose
synchronized Ensures mutual exclusion (only one thread at a time)
ReentrantLock More flexible locking mechanism
wait(), notify() Thread communication mechanisms
volatile Ensures visibility of shared variables