Java Multithreading: "Basic article" 11 of the production of consumer problems

Source: Internet
Author: User
Tags final int size printf thread

1. Production/consumer model

The production/consumer issue is a very typical multi-threaded problem involving "producer", "Consumer", "Warehouse" and "product". The relationship between them is as follows:

(01) The producer only when the warehouse is not full time production, the warehouse full will stop the production.

(02) Consumers can consume only when they have products in storage, while the Cang are waiting.

(03) When the consumer found that the storage is not available to consume when the producer will inform the production.

(04) Producers in the production of consumer products, should inform the waiting consumers to spend.

2. Production/Consumer Realization

The model is implemented by the Wait ()/notify () method (followed by other ways to implement the production/consumer model after learning the thread pool-related content). The source code is as follows:

Demo1.java//Warehouse class Depot {private int capacity;        The capacity of the warehouse private int size;
        Actual quantity of the warehouse public Depot (int capacity) {this.capacity = capacity;
    this.size = 0;
            public synchronized void Produce (int val) {a try {//left indicates the quantity you want to produce (it is possible to produce too much, you need to produce more)
            int left = val;
                while (Left > 0) {//Inventory is full, wait for "consumer" consumer product.
                while (size >= capacity) wait (); Get "Actual production quantity" (that is, the quantity added to the inventory)//if "inventory" + "quantity wanted to produce" > "Total Capacity", then "actual increment" = "Total Capacity"-"current capacity". (At this point fill the warehouse)//otherwise "actual increment" = "Quantity wanted to produce" int inc = (size+left) >capacity?
                (capacity-size): left;
                Size + + Inc;
                Left-= Inc; System.out.printf ("%s produce (%3d)--> left=%3d, inc=%3d, size=%3d\n", Thread.CurrentThread ().
                GetName (), Val, left, Inc, size);
  Notice that "consumers" can be consumed.              Notifyall ();
        The catch (Interruptedexception e) {}} is public synchronized void consume (int val) {
            try {//left indicates "customer wants to consume quantity" (it is possible that consumption is too large, inventory is insufficient, need more this consumption) int left = Val;
                while (Left > 0) {//Inventory is 0 o'clock, wait for "producer" to produce the product.
                while (size <= 0), wait (); Get the "amount of actual consumption" (that is, the amount actually reduced in inventory)//if "stock" < "the quantity that the customer wants to consume", "actual consumption" = "inventory";//otherwise, "actual consumption" = "number of customers to consume
                ”。 int dec = (size<left)?
                Size:left;
                size = Dec;
                Left-= Dec; System.out.printf ("%s consume (%3d) <--left=%3d, dec=%3d, size=%3d\n", Thread.CurrentThread ().
                GetName (), Val, left, Dec, size);
            Notifyall (); The catch (Interruptedexception e) {}} is public String toString () {return "Capacity: "+capacity+", actual sizE: "+size;
        
    }//Producer class Producer {private Depot Depot;
    Public Producer (Depot Depot) {this.depot = Depot;
    //Consumer Products: Create a new thread to produce the product in the warehouse. public void produce (final int val) {new Thread () {public void run () {Depot.produce (
            Val);
    }}.start ();
        
    }//Consumer class Customer {private Depot Depot;
    Public Customer (Depot Depot) {this.depot = Depot;
    //Consumer Products: Create a new thread to consume the product from the warehouse. public void consume (final int val) {new Thread () {public void run () {Depot.consume (
            Val);
    }}.start ();
        } public class Demo1 {public static void main (string[] args) {Depot mdepot = new Depot (100);
        Producer Mpro = new Producer (mdepot);
    
        Customer MCUs = new Customer (mdepot);
        Mpro.produce (60);
        Mpro.produce (120);
        Mcus.consume (90); Mcus.coNsume (150);
    Mpro.produce (110); }
}

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.