Thread Creation and Management
1. Basic Threading Concepts
Thread Creation Methods
Extending Thread class
javaCopyclass MyThread extends Thread {
public void run() {
// thread code here
}
}
// Usage
MyThread thread = new MyThread();
thread.start();
Implementing Runnable interface
javaCopyclass MyRunnable implements Runnable {
public void run() {
// thread code here
}
}
// Usage
Thread thread = new Thread(new MyRunnable());
thread.start();
Anonymous Runnable
javaCopyThread thread = new Thread(new Runnable() {
public void run() {
// thread code here
}
});
Lambda Expression (Java 8+)
javaCopyThread thread = new Thread(() -> {
// thread code here
});
Thread Lifecycle
NEW: Thread object created but not yet started
RUNNABLE: Thread executing in JVM
BLOCKED: Waiting for monitor lock
WAITING: Waiting indefinitely for another thread
TIMED_WAITING: Waiting for specified time
TERMINATED: Thread completed execution
Basic Thread Methods
javaCopythread.start(); // Start thread execution
thread.run(); // Run thread code (don't call directly)
thread.sleep(1000); // Sleep for 1000ms
thread.join(); // Wait for thread completion
thread.interrupt(); // Interrupt thread
thread.isAlive(); // Check if running
thread.setPriority(Thread.MAX_PRIORITY); // Set priority
2. Intermediate Concepts
Thread Synchronization
synchronized keyword
javaCopy// Method level
synchronized void method() {
// synchronized code
}
// Block level
synchronized(object) {
// synchronized code
}
volatile keyword
javaCopyprivate volatile boolean flag = false;
Object-level locking
javaCopyprivate final Object lock = new Object();
public void method() {
synchronized(lock) {
// synchronized code
}
}
Thread Communication
javaCopy// Wait and Notify
synchronized(object) {
while(condition) {
object.wait();
}
// do something
object.notify();
}
Thread Pool
javaCopy// Fixed Thread Pool
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
// task code
});
// Cached Thread Pool
ExecutorService executor = Executors.newCachedThreadPool();
// Scheduled Thread Pool
ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
3. Advanced Concepts
Lock Interface
javaCopyprivate final ReentrantLock lock = new ReentrantLock();
public void method() {
lock.lock();
try {
// critical section
} finally {
lock.unlock();
}
}
ReadWriteLock
javaCopyprivate final ReadWriteLock rwLock = new ReentrantReadWriteLock();
public void read() {
rwLock.readLock().lock();
try {
// read operation
} finally {
rwLock.readLock().unlock();
}
}
Atomic Classes
javaCopyprivate AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet(); // Thread-safe increment
CompletableFuture (Java 8+)
javaCopyCompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> "Result")
.thenApply(s -> s + " processed")
.thenAccept(System.out::println);
ThreadLocal
javaCopyprivate ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
threadLocal.set(value);
Integer value = threadLocal.get();
4. Common Interview Questions
What is thread safety?
Thread safety ensures that code behaves correctly when accessed by multiple threads simultaneously
Achieved through synchronization, atomic operations, immutable objects
Difference between process and thread?
Process: Independent execution unit with its own memory space
Thread: Lightweight unit sharing process memory space
What is deadlock?
Situation where two or more threads are blocked forever, waiting for each other
javaCopy// Deadlock example
synchronized(lockA) {
synchronized(lockB) {
// Thread 1 code
}
}
// Meanwhile in another thread
synchronized(lockB) {
synchronized(lockA) {
// Thread 2 code
}
}
How to prevent deadlock?
Lock ordering
Lock timeouts
Deadlock detection
Using tryLock()
Difference between wait() and sleep()?
wait() releases lock, sleep() doesn't
wait() called on Object, sleep() called on Thread
wait() needs synchronization, sleep() doesn't
What is thread dumping?
Snapshot of the state of all threads in JVM
Used for debugging threading issues
Can be generated using jstack tool
Explain the producer-consumer problem
javaCopyclass Buffer {
private Queue<Integer> queue = new LinkedList<>();
private int size;
public synchronized void produce(int item) throws InterruptedException {
while(queue.size() == size) {
wait();
}
queue.add(item);
notify();
}
public synchronized int consume() throws InterruptedException {
while(queue.isEmpty()) {
wait();
}
int item = queue.remove();
notify();
return item;
}
}
5. Best Practices
Always release locks in finally block
Avoid using Thread.stop() (deprecated)
Minimize synchronized scope
Prefer concurrent collections over synchronized collections
Use thread pools instead of creating threads manually
Handle InterruptedException properly
Avoid using Thread.sleep() in production code
Use atomic classes for simple counters
Implement proper exception handling in threads
Use thread-safe collections when needed (ConcurrentHashMap, CopyOnWriteArrayList)
6. Common Threading Problems
Race Conditions
Memory Visibility Issues
Deadlocks
Livelocks
Thread Starvation
Priority Inversion
7. Debugging Tips
Use Thread.currentThread().getStackTrace()
Enable thread debugging in IDE
Use jstack for thread dumps
Monitor thread states
Use logging in critical sections
Use Java Flight Recorder for detailed analysis
Last updated