Concurrency
concurrency7ProducerConsumer
- Path
- pkg7concurrency/concurrency7ProducerConsumer.java
- Package
- pkg7concurrency
- Study order
- 7
- Run
- Single-file source launch
- Command
- java pkg7concurrency/concurrency7ProducerConsumer.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg7concurrency;2 3/*4 * concurrency7ProducerConsumer.java5 * ---------------------6 * The classic producer/consumer problem solved with a BlockingQueue, which7 * handles all the waiting/signaling for you (no manual wait/notify).8 *9 * BlockingQueue.put() blocks when full; take() blocks when empty.10 * A "poison pill" signals consumers to stop.11 */12import java.util.concurrent.*;13import java.util.concurrent.atomic.AtomicInteger;14 15public class concurrency7ProducerConsumer {16 17 private static final int POISON = -1;18 19 public static void main(String[] args) throws InterruptedException {20 BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10); // bounded buffer21 AtomicInteger consumedSum = new AtomicInteger();22 int items = 20, consumers = 3;23 24 // Producer25 Thread producer = new Thread(() -> {26 try {27 for (int i = 1; i <= items; i++) queue.put(i); // blocks if full28 for (int c = 0; c < consumers; c++) queue.put(POISON); // stop signals29 } catch (InterruptedException ignored) {}30 }, "producer");31 32 // Consumers33 Thread[] cons = new Thread[consumers];34 for (int c = 0; c < consumers; c++) {35 cons[c] = new Thread(() -> {36 try {37 while (true) {38 int v = queue.take(); // blocks if empty39 if (v == POISON) return;40 consumedSum.addAndGet(v);41 }42 } catch (InterruptedException ignored) {}43 }, "consumer-" + c);44 }45 46 producer.start();47 for (Thread t : cons) t.start();48 producer.join();49 for (Thread t : cons) t.join();50 51 int expected = items * (items + 1) / 2; // 1..20 sum = 21052 System.out.println("consumed sum = " + consumedSum.get() + " (expected " + expected + ")");53 System.out.println("match: " + (consumedSum.get() == expected));54 }55}