Saturday, February 4, 2023

Producer-Consumer using CountdownLatch

 

Here is an example of a producer-consumer scenario using CountdownLatch in Java:

java
import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; public class ProducerConsumer { private static final int NUM_PRODUCERS = 3; private static final int NUM_CONSUMERS = 2; private static final int NUM_ITEMS = 20; private static final LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>(); private static final CountDownLatch startSignal = new CountDownLatch(1); private static final CountDownLatch endSignal = new CountDownLatch(NUM_PRODUCERS + NUM_CONSUMERS); public static void main(String[] args) { // Start the producers for (int i = 0; i < NUM_PRODUCERS; i++) { new Thread(new Producer()).start(); } // Start the consumers for (int i = 0; i < NUM_CONSUMERS; i++) { new Thread(new Consumer()).start(); } // Wait for the producers to finish producing items startSignal.countDown(); try { endSignal.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private static class Producer implements Runnable { @Override public void run() { try { startSignal.await(); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < NUM_ITEMS; i++) { try { queue.put(i); } catch (InterruptedException e) { e.printStackTrace(); } } endSignal.countDown(); } } private static class Consumer implements Runnable { @Override public void run() { try { startSignal.await(); } catch (InterruptedException e) { e.printStackTrace(); } while (!queue.isEmpty()) { try { System.out.println("Consumed: " + queue.take()); } catch (InterruptedException e) { e.printStackTrace(); } } endSignal.countDown(); } } }

In this example, we have three producers and two consumers, and each producer produces 20 items. The main thread starts the producers and consumers and waits for them to finish using the endSignal countdown latch.

The producers and consumers are synchronized using the startSignal countdown latch. The producers and consumers wait for the main thread to release the start signal before they start running.

The producers add items to the queue, and the consumers take items from the queue and print them. When all items are consumed, the consumers decrement the endSignal countdown latch to signal that they have finished.


No comments:

Post a Comment