java thread producer and consumer model

Multithread Communication - Producer-Consumer Model

Producer-consumer pattern is not one of the 23 design patterns proposed by GOF. All the 23 design patterns are based on object-oriented, but there are many efficient programming patterns in process-oriented programming. Producer-consumer pattern is one of them. It is the most commonly used design pattern in our programming process.
What kind of problems does the producer-consumer model arise to solve? In the actual software development process, we often encounter the following scenarios: one module is responsible for generating data, and the other module is responsible for processing the data (the module here is broad, can be classes, functions, threads, processes, etc.). The module that produces data is called the producer, and the module that processes data is called the consumer. The abstraction of producers and consumers alone is not enough to be the producer/consumer model. The model also needs to have a buffer between producers and consumers as an intermediary. The producer puts the data in the buffer, while the consumer takes the data out of the buffer.

Principle description of producer-consumer model:
(1) The producer only produces when the warehouse is not full, and stops production when the warehouse is full.
(2) Consumers can only consume when they have products in storage, but when they are empty, they wait.
(3) Consumers will inform producers when they find that there is no product in storage for consumption.
(4) When producing consumable products, producers should notify waiting consumers to consume.

Advantages of the producer-consumer model:
(1) Separate the production module from the consumption module, which reduces the coupling of the program and facilitates the expansion and maintenance of the program.
(2) Separating the production module from the consumption module can make the operation of the production module no longer depend on the execution of the consumption module, instead of synchronous execution to asynchronous execution, and both can support concurrency, thus greatly improving the efficiency of the program.
(3) The data produced by the producer is stored in the buffer, and consumers can take out data processing according to their own logic, thus effectively avoiding the problem of uneven load of task execution in the consumption module.

Now I'm going to write a classic example.

/** 
* @author Dong Shuo: 
* @version Creation time: August 14, 2017, 7:20:49 p.m. 
*  
*/

public class Baozi {
    private int count;//Statistics on how many steamed buns were produced

    public Baozi() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Baozi(int count) {
        super();
        this.count = count;
    }

    @Override
    public String toString() {
        return "Baozi [count=" + count + "]";
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
package com.ds.thread;
/** 
* @author Dong Shuo: 
* @version Creation time: August 14, 2017, 7:17:04 p.m. 
* Intermediate Containers Connect Producers with Consumers
*/

public class ArrayPage {
    private int index=0;   //Array subscript
    private Baozi []baozis=new Baozi[12];//Array containers are used to hold buns
    /**Production of baozi */
    public synchronized void  add(Baozi baozi) 
    {
        while(index==baozis.length)
        {
            System.out.println("The cage is full.");
            try {
                wait();                             //Waiting to consume steamed buns
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        notify();                                   //Continue to produce steamed buns
        baozis[index]=baozi;
        index++;
        System.out.println("Already produced"+baozi.getCount()+"Baozi,In the cage"+index+"Baozi");


    }
    /**Consume buns*/
    public synchronized void consume()
    {   
        while (index==0) {
            System.out.println("There are no steamed buns in the cage.");
            try {
                wait();                         //Waiting for the production of steamed buns
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        notify();
        index--;
        Baozi baozi=    baozis[index];
        System.out.println("The first"+baozi.getCount()+"The steamed bun was eaten.,There are also some cages."+index+"Baozi");
    }

}
package com.ds.thread;
/** 
* @author Dong Shuo: 
* @version Creation time: August 14, 2017, 7:43:35 p.m. 
*  
*/
//Producer
class Produce extends Thread
{
    private ArrayPage arrayPage;
    private int  count=1;

    public Produce(ArrayPage arrayPage) {
        super();
        this.arrayPage = arrayPage;
    }
    @Override
    public void run() {
        while(true)
        {
            Baozi  baozi=new Baozi(count++);
            arrayPage.add(baozi);

        }
    }


}
class Consume extends Thread
{
    private ArrayPage arrayPage;

    public Consume(ArrayPage arrayPage) {
        super();
        this.arrayPage = arrayPage;
    }
    @Override
    public void run() {
        while(true)
        {
            arrayPage.consume();


        }
    }



}
public class MainMethod {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayPage arrayPage=new ArrayPage();
        Produce produce=new Produce(arrayPage);
        Consume consume=new Consume(arrayPage);
        produce.start();
        consume.start();
    }

}

Keywords: Programming

Added by justcrapx on Tue, 04 Jun 2019 21:17:18 +0300