On the problem of producer and consumer in Java thread _java

Source: Internet
Author: User
Tags sleep

First, the concept

Producer and consumer issues are a golden code of multithreading collaboration problem. The producer is responsible for producing the product and storing it in the warehouse; The consumer obtains the product from the storehouse and consumes it. When the warehouse is full, the producer must stop production until the warehouse has a place to store the product, and when the warehouse is empty, the consumer must stop consuming until there is a product in the warehouse.

The main solution to the problem of producer/consumer problems is as follows: 1. Use threading to simulate the producer and keep the product in the store in the Run method. 2. Use threading to simulate the consumer and constantly get the product from the warehouse in the Run method. 3

 . Storage class to save products, when the product number is 0 o'clock, call the Wait method, make the current consumer thread into the waiting state, when there is a new product deposit, call the Notify method, wake up the waiting consumer thread. When the warehouse is full, the wait method is invoked to make the current producer thread enter the waiting state, and when a consumer acquires the product, the Notify method is invoked to awaken the waiting producer thread.

Second, the example

Package book.thread.product; public class Consumer extends thread{private Warehouse warehouse;//consumer gets the product's Warehouse private Boolean running = false;//whether a knot is required
    The flag bit public Consumer (Warehouse warehouse,string name) {super (name) of the bundle thread;
  This.warehouse = Warehouse;
    public void Start () {this.running = true;
  Super.start ();
    public void Run () {product product;
        try {while (running) {//Get product products = Warehouse.getproduct () from the warehouse;
      Sleep (500);
    } catch (Interruptedexception e) {e.printstacktrace ();
      Stop consumer thread public void Stopconsumer () {synchronized (warehouse) {this.running = false;
  Warehouse.notifyall ()//notification waiting for warehouse thread}//consumer thread is running public boolean isrunning () {return running;

}} package book.thread.product; public class Producer extends thread{private Warehouse warehouse;//producer Storage products warehouse private static int producename = 0;//production Name of the product private Boolean running = false;//whether or not to endThe thread's flag bit public Producer (Warehouse warehouse,string name) {super (name);
  This.warehouse = Warehouse;
    public void Start () {this.running = true;
  Super.start ();
    public void Run () {product product;
      Produce and store product try {while (running) {Product = new product ((++producename) + "");
      This.warehouse.storageProduct (product);
      Sleep (300);
    } catch (Interruptedexception e) {e.printstacktrace ();
      Stop producer thread public void Stopproducer () {synchronized (warehouse) {this.running = false;
    Notifies the Warehouse.notifyall () of the thread waiting for the warehouse;
  }//producer thread is running public boolean isrunning () {return running;

}} package book.thread.product;
  public class Product {private String name;//product name, public products (string name) {this.name = name;
  Public String toString () {return "product-" +name;

}} package book.thread.product; Product Warehouse class, the internal use of an array to represent the loop queue to store the product public class Warehouse {private statIC int CAPACITY = 11;//warehouse capacity private product[] products;//products in the warehouse//[front,rear] the product in the range is not consumed private int front = 0;//Current bin The subscript private int rear = The last item in the library that is not consumed in the 0;//warehouse is subscript plus 1 public Warehouse () {this.products = new product[capacity
  ];
    Warehouse (int capacity) {this ();
      if (capacity > 0) {capacity = capacity +1;
    This.products = new Product[capacity]; ///Get a product from the warehouse public products GetProduct () throws interruptedexception{synchronized (this) {Boolean cons umerrunning = true;//Flag consumer thread is still running thread CurrentThread = Thread.CurrentThread ();//Get current thread if (CurrentThread ins
      Tanceof Consumer) {consumerrunning = ((Consumer) currentthread). IsRunning (); }else{return null;//non-consumer cannot get product}//If the consumer thread is running but there is no product in the warehouse, the consumer thread continues to wait while ((front==rear) &&am P
        consumerrunning) {wait ();
      Consumerrunning = ((Consumer) currentthread). IsRunning (); //If the consumer thread has stopped running, exit the method and cancel the fetchProduct if (!consumerrunning) {return null;
      //Get the first product products = Products[front] that are not currently consumed;
      System.out.println ("consumer[" + currentthread.getname () + "] getproduct:" +product);
      Moves the subscript of the currently not-consumed product to a bit, or to the end of the array, to the first front = (front+1+capacity)%capacity;
      System.out.println ("The number of products not yet consumed in the warehouse:" + (Rear+capacity-front)%capacity);
      Notifies other waiting threads notify ();
    return product; Store a product public void storageproduct (product product) throws interruptedexception{synchronized (this) {B to the warehouse
    Oolean producerrunning = true;//Flag producer thread is running thread CurrentThread = Thread.CurrentThread ();
    if (CurrentThread instanceof Producer) {producerrunning = ((Producer) currentthread). IsRunning ();
    }else{return;
    //If the last unused product is next to the first product that is not consumed, there is no storage space.
      If there is no storage space and the producer thread is still running, the producer thread waits for the warehouse to release the product while (((rear+1)%capacity = = front) && producerrunning) {wait (); Producerrunning = ((Producer) CurreNtthread). IsRunning ();
    If the production line has stopped running, stop the product's storage if (!producerrunning) {return;
    //Save Product to warehouse products[rear] = product;
    System.out.println ("producer[" + thread.currentthread (). GetName () + "] storageproduct:" + product);
    A rear = (rear + 1)%capacity is moved after the rear cycle;
    System.out.println ("The number of products not yet consumed in the warehouse:" + (rear + Capacity-front)%capacity);
    Notify ();

}} package book.thread.product; public class Testproduct {public static void main (string[] args) {Warehouse Warehouse = new Warehouse (10);//Build a warehouse
    , the capacity of 10//establishes producer threads and consumer Producer producers1 = new Producer (warehouse, "producer-1");
    Producer producers2 = new Producer (warehouse, "producer-2");
    Producer producers3 = new Producer (warehouse, "producer-3");
    Consumer consumer1 = new Consumer (warehouse, "consumer-1");
    Consumer consumer2 = new Consumer (warehouse, "consumer-2");
    Consumer Consumer3 = new Consumer (warehouse, "consumer-3"); Consumer consumer4 = new ConsUmer (Warehouse, "consumer-4");
    Start producer thread and Consumer thread Producers1.start ();
    Producers2.start ();
    Consumer1.start ();
    Producers3.start ();
    Consumer2.start ();
    Consumer3.start ();
    Consumer4.start ();
    Let producer/consumer programs run 1600ms try {thread.sleep (1600);
    catch (Interruptedexception e) {e.printstacktrace ();
    //Stop Consumer thread producers1.stopproducer ();
    Consumer1.stopconsumer ();
    Producers2.stopproducer ();
    Consumer2.stopconsumer ();
    Producers3.stopproducer ();
    Consumer3.stopconsumer ();
  Consumer4.stopconsumer ();
 }
}

Output results:

PRODUCER[PRODUCER-1] Storageproduct:product-1 Warehouse has not been consumed in the number of products: 1 Consumer[consumer-2] Getproduct:product-1 Storage has not been consumed in the number of products: 0 Producer[producer-3] Storageproduct:product-3 Warehouse has not been consumed in the number of products: 1 Producer[producer-2] Storageproduct :P Roduct-2 Warehouse has not been consumed in the number of products: 2 consumer[consumer-3] getproduct:product-3 Warehouse has not been consumed in the number of products: 1 Consumer[consumer-1] Getproduct:product-2 Warehouse has not been consumed in the number of products: 0 Producer[producer-1] Storageproduct:product-4 Warehouse has not been consumed by the number of products: 1 consumer[
CONSUMER-4] Getproduct:product-4 Warehouse has not been consumed in the number of products: 0 Producer[producer-3] Storageproduct:product-6 Warehouse has not been consumed by the number of products: 1
PRODUCER[PRODUCER-2] Storageproduct:product-5 Warehouse has not been consumed in the number of products: 2 consumer[consumer-1] Getproduct:product-6 The number of products not yet consumed in the warehouse: 1 Consumer[consumer-2] getproduct:product-5 Warehouse has not been consumed by the number of products: 0 Producer[producer-1] Storageproduct: Product-7 Warehouse has not been consumed in the number of products: 1 Consumer[consumer-3] getproduct:product-7 Warehouse has not been consumed in the number of products: 0 producer[producer-3] Storageproduct:product-8 Warehouse has not been consumed in the number of products: 1 Producer[producer-2] storageproduct:product-9 Warehouse has not been consumed by the number of products: 2 consumer[ Consumer-4] Getproduct:product-8 Warehouse has not been consumed in the number of products: 1 Producer[producer-1] STORAGEPRODUCT:PRODUCT-10 Warehouse has not been consumed in the number of products: 2 producer[
PRODUCER-3] STORAGEPRODUCT:PRODUCT-11 Warehouse has not been consumed in the number of products: 3 Producer[producer-2] Storageproduct:product-12 The number of products not yet consumed in the warehouse: 4 Consumer[consumer-1] Getproduct:product-9 Warehouse has not been consumed by the number of products: 3 Consumer[consumer-2] GetProduct: PRODUCT-10 Warehouse has not been consumed in the number of products: 2 consumer[consumer-3] getproduct:product-11 Warehouse has not been consumed in the number of products: 1 producer[producer-3] STORAGEPRODUCT:PRODUCT-13 Warehouse has not been consumed in the number of products: 2 producer[producer-1] STORAGEPRODUCT:PRODUCT-14 Warehouse has not been consumed by the number of products: 3 Producer
[Producer-2] Storageproduct:product-15 Warehouse has not been consumed in the number of products: 4 Consumer[consumer-4] GETPRODUCT:PRODUCT-12 Warehouse has not been consumed by the number of products: 3
CONSUMER[CONSUMER-1] GETPRODUCT:PRODUCT-13 Warehouse has not been consumed in the number of products: 2 consumer[consumer-2] Getproduct:product-14 The number of products not yet consumed in the warehouse: 1 Producer[producer-1] storageproduct:product-16 Warehouse has not been consumed in the number of products: 2 producer[producer-3] STORAGEPRODUCT:PRODUCT-17 Warehouse has not been consumed in the number of products: 3 Producer[producer-2] STORAGEPRODUCT:PRODUCT-18 Warehouse has not been consumed in the number of products: 4

Analysis: A product warehouse was established in the main method, and the warehouse was not associated with 3 producer threads and 4 consumer threads, which enabled the producer/consumer model to work, and when the program ran 1600ms, all producers stopped producing the product, Consumers stop consuming products.

Producer Thread product produces a product without 300ms in the Run method and is stored in a warehouse; the consumer thread consumer a product from the warehouse without 500ms in the Run method.

Warehouse Class warehouse is responsible for storing products and distributing products. The Storageproduct method is responsible for storing the product, and when the warehouse is full, the current thread enters the waiting state, that is, if producer thread A finds the warehouse full and cannot be stored when it calls the Storageproduct method to store the product, it enters the wait state. When the storage product succeeds, call the Notify method and wake up the waiting consumer thread.

The GetProduct method is responsible for the advance of the product, when the warehouse is empty, the current thread enters the waiting state, that is, if the consumer thread B calls the GetProduct method to obtain the product, it finds that the warehouse is empty and then enters the wait state. When the extraction product succeeds, call the Notify method and wake up the waiting producer thread.

The above article on the Java thread producers and consumers of the problem is to share all the content of the small, hope to give you a reference, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.