Java Multi-Threaded series Foundation (11) of the production of 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:

  1//Demo1.java 2//Warehouse 3 class Depot {4 private int capacity;        Capacity of the warehouse 5 private int size;  Actual number of warehouses 6 7 public Depot (int capacity) {8 this.capacity = capacity; 9 this.size = 0; Ten} one public synchronized void produce (int val) {try {+//left indicates "quantity to be produced" (it is possible to produce The volume is too much, it needs to be produced more) int left = Val; When the (left > 0) {17//inventory is full, wait for "consumer" consumer products. while (size >= capacity) wait (); 20//Get "Actual production quantity" (i.e. new quantity in stock) 21//If "inventory" + "quantity to produce" > "Total Capacity", then "actual increment" = "Total Capacity"-"current capacity". (Fills the warehouse at this time) 22//otherwise "actual increment" = "Quantity to be produced" (Size+left) >capacity? (capacity-size): left; Size + = Inc; + Left-to-= Inc; System.out.printf ("%s produce (%3d)--left=%3d, Inc=%3d, size=%3d\n", T Hread.currentthreaD (). GetName (), Val, left, Inc, size); 28//Notify "consumers" to consume. Notifyall (); (Interruptedexception e) {+}--synchronized void  Consume (int val) {$ try {PNS//left indicates "customer wants to consume quantity" (may consume too much, inventory is not enough, need more this consumption) int left = Val; (Left > 0) {40//stock is 0 o'clock, waiting for "producer" to produce products. The while (size <= 0), wait ();                 43//Get the "quantity actually consumed" (i.e. the quantity actually reduced in inventory) 44//If "inventory" < "quantity that the customer wants to consume", then "actual consumption" = "inventory"; 45 Otherwise, "actual consumption" = "Quantity to be consumed by the customer". size<left int dec = (a)? Size:left; size = Dec; -= Dec; System.out.printf ("%s consume (%3d) <--left=%3d, dec=%3d, size=%3d\n", Hread.currentthread (). GetName (), Val, left, Dec, size); Wuyi Notifyall (); 52}(interruptedexception e) {SI} * * * * * * * * * * * * * * String toString () {retur N "Capacity:" +capacity+ ", Actual size:" +size;  59} 60} 61 62//Producer Producer class {Depot Depot; n-Producer (Depot Depot) { This.depot = depot; 68} 69 70//Consumer product: Create a new thread to produce the product in the warehouse.                 Produce public void (final int val) {$ new Thread () {$ public void run () {74 Depot.produce (Val); }.start} (); 77} 78} 79 80//Consumer Bayi class Customer {Depot private Depot, Depot public Customer (Depot) { This.depot = depot; 86} 87 88//Consumer product: Create a new thread to consume the product from the warehouse.                 Consume public void (final int val) {new Thread () {92 Depot.consume (Val); 94}.start (); 98 public class Demo1 {$ public static void MAin (string[] args) {Depot mdepot = new Depot, 101 Producer mpro = new Producer (mdepot); 102 Customer MCus = new Customer (Mdepot), 103 104 mpro.produce (mpro.produce); 106 mcus.co Nsume (107 mcus.consume); 108 mpro.produce (110); 109}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, all threads that synchronize the lock are awakened through Notifyall (), including " Producer Thread ", what we call" informing producers of production ".

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

Reprint:http://www.cnblogs.com/skywang12345/p/3480016.html

Java Multi-Threaded series Foundation (11) of the production of consumer issues

Related Article

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.