Java Multithreading--"plain edition" producer consumer Issues

Source: Internet
Author: User
Tags int size

1. Production/consumer model

Production/consumer issues are a very typical multithreaded problem, involving the "producer", "Consumer", "Warehouse" and "product". The relationship between them is as follows:
(01) The producer will stop production only when the storage is not full and the warehouse is full.
(02) Consumers can only consume goods when they are in storage, while Cang wait.
(03) When consumers find that storage products can be consumed when the production will be notified to producers.
(04) Producers in the production of consumable products, should inform the waiting consumers to spend.

2. Production/Consumer realization

The model is implemented using the Wait ()/notify () method ( later, after learning about the thread pool, the production/consumer model is implemented in other ways ). The source code is as follows:

demo1.java//Warehouse class Depot {private int capacity;        The capacity of the warehouse private int size;        The actual number of warehouses public Depot (int capacity) {this.capacity = capacity;    this.size = 0; } public synchronized void produce (int val) {try {//left means "quantity to be produced" (it is possible to produce too much to produce more) I            NT left = val;                while (Left > 0) {//Inventory is full, wait for "consumer" consumer products.                while (size >= capacity) wait (); Get "Actual production quantity" (i.e. new quantity in inventory)//if "inventory" + "quantity to produce" > "Total Capacity", then "actual increment" = "Total Capacity"-"current capacity". (Fills the warehouse at this time)//otherwise "actual increment" = "Quantity to be produced" int inc = (size+left) >capacity?                (capacity-size): left;                Size + = Inc;                Left-to-= Inc; System.out.printf ("%s produce (%3d)--left=%3d, Inc=%3d, size=%3d\n", Thread.CurrentThread (). g                Etname (), Val, left, Inc, size);                Inform "consumers" to consume.           Notifyall (); }} catch (Interruptedexception e) {}} public synchronized void consume (int val) {try {            Left means "customer wants to consume quantity" (may consume too much, inventory is not enough, need to spend more this) int left = Val;                while (Left > 0) {//stock is 0 o'clock, wait for "producer" to produce the product.                while (size <= 0) wait ();                 Get the "Quantity actually consumed" (that is, the quantity actually reduced in the inventory)//if "inventory" < "quantity that the customer wants to consume", then "actual consumption" = "inventory";//otherwise, "actual consumption" = "Quantity to be consumed by customer". 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 (). g                Etname (), Val, left, Dec, size);            Notifyall (); }} catch (Interruptedexception e) {}} 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 products 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); }}

Description :
producer is a "producer" class, which is associated with a "warehouse (depot)". When the produce () method of the producer is called, it creates a new thread and produces the product in the warehouse.
customer is a "consumer" class, which is associated with "warehouse (depot)". When the consume () method of the "consumer" is called, it creates a new thread and consumes the products in the "warehouse".
Depot is the "warehouse" class, which records "warehouse capacity (capacity)" and "current number of products in the warehouse (size)" in the warehouse.
The production method of the "Warehouse" class produce () and the consumption method consume () method are synchronized methods that enter the Synchronized method body, which means that the thread obtains the synchronization lock for the "warehouse" object. This means that at the same time, producers and consumer threads can only have one run. Through the synchronous lock, it realizes the mutually exclusive access to "cruelty".
for the production method produce () : When the warehouse is full, the producer thread waits and waits for the consumer to consume the product before the production line can be produced; After the producer thread has finished producing the product, all threads that synchronize the lock are awakened through Notifyall (), including " Consumer thread ", what we call" informing consumers of consumption ".
for consumption method consume () : When the warehouse is empty, the consumer thread waits, waits for the producer to produce the product, the consumer thread can consume; After the consumer thread consumes the product, it passes the Notifyall () Wake up all threads of the sync lock, including "producer Threads", which we call "notify producers to produce".

Run results (one time) :

Thread-0 Produce ()--left=  0, inc=, size= 60thread-4 Produce (+)--left=, inc=, size=100thread- 2 Consume (<--) left=  0, dec=, size= 10thread-3 consume (<--left=140, dec=, size= 0thread-1  PR Oduce---left=, inc=100, size=100thread-3 consume (All) <--left=, dec=100, size=  0thread-4 Produce (1 --left=  0, inc=, size= 70thread-3 consume (120) <--left=  0, dec=, size= 30thread-1 Produce  --left= 0, inc=, size= 50

Java Multithreading--"plain edition" producer consumer Issues

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.