Java Multithreading Series--"basic article" 11 of the production of consumer issues

Source: Internet
Author: User

Overview

In this chapter, "Production/consumer issues" are discussed. The topics covered include:
1. Production/consumer model
2. Production/Consumer Realization

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

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.java2//Warehouse3ClassDepot {4Privateint capacity;//Capacity of the Warehouse5Privateint size;//Actual number of warehouses67Public Depot (Intcapacity) {8This.capacity =capacity;9This.size = 0;10}1112PublicSynchronizedvoid Produce (IntVal) {13Try{14//Left means "the quantity you want to produce" (it is possible to produce too much, it needs more production)15int left =Val16while (Left > 0) {17//When inventory is full, wait for "consumer" consumer products.18while (size >=capacity)19Wait ();20//Get "Actual production quantity" (that is, new quantity in inventory)21st//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"23int inc = (size+left) >capacity? (capacity-Size): Left;Size + =Inc;-Left-=Inc;System.out.printf ("%s produce (%3d)--left=%3d, inc=%3d, size=%3d\n",27Thread.CurrentThread (). GetName (), Val, left, Inc, size);28//Inform "consumers" to consume.29Notifyall ();30}31}Catch(Interruptedexception e) {32}33}3435PublicSynchronizedvoid Consume (IntVal) {36Try{37//Left means "customer wants to consume quantity" (may consume too much, inventory is not enough, need to spend more)38int left =Val39while (Left > 0) {40//Stock is 0 o'clock, waiting for "producer" to produce products.41while (size <= 0)42Wait ();43//Get the "Quantity actually consumed" (that is, the quantity actually reduced in the inventory)44//"Actual Consumption" = "Inventory" if "inventory" < "quantity to be consumed by customer";45//Otherwise, "actual consumption" = "Quantity to be consumed by the customer".46int dec = (size<left)?Size:left;Size-=Dec-Left-=DecSystem.out.printf ("%s consume (%3d) <--left=%3d, dec=%3d, size=%3d\n",50Thread.CurrentThread (). GetName (), Val, left, Dec, size);51Notifyall ();52}53}Catch(Interruptedexception e) {54}55}5657PublicString toString () {58Return "Capacity:" +capacity+ ", Actual size:" +Size59}60}6162//Producers63ClassProducer {64PrivateDepot Depot;6566PublicProducer (Depot Depot) {67This.depot =Depot68}6970//Consumer Products: Create a new thread to produce products in the warehouse.71Publicvoid Produce (FinalInt Val) { new Thread () { public void run () { Depot.produce (Val); }.start} (); 77} 78} 79 80//Consumer Bayi class Customer {Depot private Depot, Depot public Customer (Depot) {this.depot = de Pot 86} 87 88//Consumer product: Create a new thread to consume the product from the warehouse. Consume public void (final int val) {$ new Thread () {depot.consume public void Run () {94}.start (val); 98 public class Demo1 {a public static void main (string[] args) {Depot mdepot = new Depot (+); 101 Pr Oducer Mpro = new Producer (mdepot); 102 Customer MCus = new Customer (Mdepot); 103 104 Mpro.produce ($); Mpro.produce (120) ; 106 Mcus.consume; 107 Mcus.consume (108 mpro.produce); 109}110}      

Description
producer is the "producer" class, which is associated with "warehouse (depot)". When the produce () method of the producer is called, it creates a new thread and produces the product in the warehouse.
        "Warehouse" class production methods produce () and consumption method consume () methods are synchronized methods , entering the Synchronized method body means that the thread obtains the synchronization lock for the "warehouse" object.         for production method produce () : When the warehouse is full, the producer thread Waits, A production line is required to wait for the consumer to consume the product, and after the producer thread has finished producing the product, all threads that synchronize the lock are awakened through Notifyall (), including "Consumer threads", what we call "notifying consumers to consume".
      for consumption method consume () : When the warehouse is empty, the consumer thread waits, The consumer thread is required to wait for the producer to produce the product, and after the consumer thread consumes the product, all threads that synchronize the lock are awakened through Notifyall (), including "producer Threads", which we call "notify the producer for production".

Run results (one time) :

Thread-0 Produce ()--left=  0, inc=, size= Thread-4 produce(+)--left=, inc=, Size=100
    
     thread-2 consume (<--) left= 0, dec=, size= Thread-3 consume  
     (<--)  left=140 dec= 0Thread-1 Produce (+)--left=, inc=100, size=100 Thread-3consume (<--left=), dec=100, Size=
        0Thread-4 Produce (+)--left= 0, inc=, size= (Thread-3 consume) <--left= 0, dec=, size= Thread-1 Produce (0)--left=, inc=, size=       
    

Java Multithreading Series--"basic article" 11 of the production of 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.