Concurrency in Java
Java provides rich APIs for handling multithreading and concurrent programming. These allow programs to make better use of system resources and handle multiple tasks simultaneously.
⚠️ Concurrency is powerful but hard to get right — race conditions and deadlocks can ruin your day!
Creating Threads
public class MyThread extends Thread {
public void run() {
System.out.println("Running in thread: " + Thread.currentThread().getName());
}
}
Thread t = new MyThread();
t.start();
Using Runnable
Runnable task = () -> System.out.println("Runnable Task");
new Thread(task).start();
Thread Lifecycle
- New
- Runnable
- Running
- Blocked/Waiting
- Terminated
Synchronization
public synchronized void increment() {
count++;
}
Locks and Executors
Lock lock = new ReentrantLock();
lock.lock();
try {
// critical section
} finally {
lock.unlock();
}
ExecutorService executor = Executors.newFixedThreadPool();
executor.submit(() -> doWork());
executor.shutdown();


