Implementing producer-consumer
I'm thinking about how to set up a bounded buffer with a size of 10. For each producer, I’ll create a new thread that handles the producer logic. I also need to do the same for consumers while ensuring they sleep for small, random intervals. It will be important to mention fairness and briefly explain that aspect. I should respond clearly with both the explanation and the code, keeping it concise and focused on the essentials. Below is a classic multi-threaded producer–consumer solution with a bounded buffer in Java, using wait() / notifyAll() for synchronization.
import java.util.Random;
public class ProducerConsumerExample {
// Generic bounded buffer (multiple producers, multiple consumers, thread-safe)
static class BoundedBuffer<T> {
private final Object[] items;
private int putPtr = 0; // next index to put
private int takePtr = 0; // next index to take
private int count = 0; // number of items in the buffer
public BoundedBuffer(int capacity) {
items = new Object[capacity];
}
public synchronized void put(T item) throws InterruptedException {
// Wait while buffer is full
while (count == items.length) {
wait();
}
items[putPtr] = item;
putPtr = (putPtr + 1) % items.length;
count++;
// Signal a waiting consumer that an item is available
notifyAll();
}
@SuppressWarnings("unchecked")
public synchronized T take() throws InterruptedException {
// Wait while buffer is empty
while (count == 0) {
wait();
}
T item = (T) items[takePtr];
items[takePtr] = null; // optional: help GC
takePtr = (takePtr + 1) % items.length;
count--;
// Signal a waiting producer that there is space available
notifyAll();
return item;
}
}
// Producer task
static class Producer implements Runnable {
private final BoundedBuffer<Integer> buffer;
private final int id;
private final int numItems;
private final Random rnd = new Random();
public Producer(BoundedBuffer<Integer> buffer, int id, int numItems) {
this.buffer = buffer;
this.id = id;
this.numItems = numItems;
}
@Override
public void run() {
try {
for (int i = 0; i < numItems; i++) {
int value = id * 1000 + i; // unique-ish value per producer
buffer.put(value);
System.out.println("Producer " + id + " produced " + value);
// Simulate variable production time
Thread.sleep(rnd.nextInt(200));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Producer " + id + " interrupted");
}
}
}
// Consumer task
static class Consumer implements Runnable {
private final BoundedBuffer<Integer> buffer;
private final int id;
private final int numItems;
private final Random rnd = new Random();
public Consumer(BoundedBuffer<Integer> buffer, int id, int numItems) {
this.buffer = buffer;
this.id = id;
this.numItems = numItems;
}
@Override
public void run() {
try {
for (int i = 0; i < numItems; i++) {
Integer value = buffer.take();
System.out.println("Consumer " + id + " consumed " + value);
// Simulate variable consumption time
Thread.sleep(rnd.nextInt(300));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Consumer " + id + " interrupted");
}
}
}
public static void main(String[] args) throws InterruptedException {
final int BUFFER_CAPACITY = 10;
final int NUM_PRODUCERS = 3;
final int NUM_CONSUMERS = 2;
final int ITEMS_PER_PRODUCER = 20;
BoundedBuffer<Integer> buffer = new BoundedBuffer<>(BUFFER_CAPACITY);
Thread[] producers = new Thread[NUM_PRODUCERS];
Thread[] consumers = new Thread[NUM_CONSUMERS];
// Start producers
for (int i = 0; i < NUM_PRODUCERS; i++) {
producers[i] = new Thread(new Producer(buffer, i, ITEMS_PER_PRODUCER));
producers[i].start();
}
// Each consumer will consume totalItems / NUM_CONSUMERS (assuming divisible)
int totalItems = NUM_PRODUCERS * ITEMS_PER_PRODUCER;
int itemsPerConsumer = totalItems / NUM_CONSUMERS;
// Start consumers
for (int i = 0; i < NUM_CONSUMERS; i++) {
consumers[i] = new Thread(new Consumer(buffer, i, itemsPerConsumer));
consumers[i].start();
}
// Wait for all producers and consumers to finish
for (Thread t : producers) {
t.join();
}
for (Thread t : consumers) {
t.join();
}
System.out.println("All producers and consumers have finished.");
}
}
Key points:
BoundedBuffer enforces the bounded capacity.
put() waits if the buffer is full; take() waits if empty.
synchronized, wait(), and notifyAll() provide mutual exclusion and coordination.
- Works for multiple producers and multiple consumers safely.
If you’d like a version using semaphores or in C with pthread_mutex and pthread_cond, I can provide that as well.