Producer and Consumer

The producer / consumer design pattern is a pre-designed solution to separate the two main components by placing a queue in the middle, letting the producers and the consumers execute in different threads.

The Producer and Consumer Design Patterns

The producer/consumer design pattern is a pre-designed solution to separate the two main components by placing a queue in the middle. - by Andres Navarro

Source: https://dzone.com/articles/producer-consumer-design

Using java.util.concurrent.BlockingQueue;

Producer

package com.test.multithread;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TaskProducer extends Thread {
    private boolean blnExit = false;
    private final List < TaskConsumer > consumers;
    private final BlockingQueue < Long > sharedQueue;
    public TaskProducer(final BlockingQueue < Long > sharedQueue,
        final List < TaskConsumer > consumers) {
        this.sharedQueue = sharedQueue;
        this.consumers = consumers;
    }
    @Override
    public void run() {
        long i = 0;
        ////////////////////////////////////////////
        // PRODUCING THE OBJECTS TO BE CONSUMED
        ////////////////////////////////////////////
        while (!blnExit) {
            try {
                i++;
                sharedQueue.put(Long.valueOf(i));
            } catch (final InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        /////////////////////////////////
        // WAIT UNTIL THE QUEUE IS EMPTY
        /////////////////////////////////
        while (sharedQueue.size() > 0) {
            try {
                Thread.sleep(200);
                System.out.println("Producer waiting to end.");
            } catch (final InterruptedException e) {
                break;
            }
        }
        ////////////////////////////////////////////
        // SEND TO ALL CONSUMERS THE EXIT CONDITION
        ////////////////////////////////////////////
        for (final TaskConsumer consumer: consumers) {
            consumer.setExitCondition(true);
        }
    }
}

Consumer

Together

Output:

Java Lock and Condition Example using Producer Consumer Solution

-

Read more: https://javarevisited.blogspot.com/2015/06/java-lock-and-condition-example-producer-consumer.html#ixzz5gcGd1oXQ

Reference and Reading List

The Producer and Consumer Design Patterns

Producer–consumer problem - Wikipedia

Lecture 17: Concurrency—Producer/Consumer Pattern and Thread

Producer-Consumer solution using threads in Java - GeeksforGeeks

Producer Consumer Design Pattern | Code Pumpkin

Last updated

Was this helpful?