public class WaitNotifyExample {
private synchronized void producerMethod() throws InterruptedException {
while (condition) {
// Thread goes to waiting state
wait();
}
// Perform production
notify(); // Notify waiting consumer
}
private synchronized void consumerMethod() throws InterruptedException {
while (anotherCondition) {
// Thread goes to waiting state
wait();
}
// Perform consumption
notify(); // Notify waiting producer
}
}
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class BlockingQueueExample {
private BlockingQueue queue =
new LinkedBlockingQueue<>(10);
public void producer() throws InterruptedException {
for (int i = 0; i < 100; i++) {
// Blocks if queue is full
queue.put(i);
}
}
public void consumer() throws InterruptedException {
while (true) {
// Blocks if queue is empty
Integer item = queue.take();
processItem(item);
}
}
}
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConditionVariableExample {
private final Lock lock = new ReentrantLock();
private final Condition dataAvailable = lock.newCondition();
private boolean hasData = false;
public void producer() throws InterruptedException {
lock.lock();
try {
while (hasData) {
// Wait if data is not consumed
dataAvailable.await();
}
// Produce data
hasData = true;
dataAvailable.signal();
} finally {
lock.unlock();
}
}
public void consumer() throws InterruptedException {
lock.lock();
try {
while (!hasData) {
// Wait if no data is available
dataAvailable.await();
}
// Consume data
hasData = false;
dataAvailable.signal();
} finally {
lock.unlock();
}
}
}