Two ways to realize the model of producer and consumer

Source: Internet
Author: User

1. Wait & Notify Method:

public class Waitandnotify {private final int max_size = 100;    Private linkedlist<object> list = new linkedlist<object> ();            public void produce (int num) {synchronized (list) {while (list.size () + num > Max_size) {System.out.println ("number of products to be produced:" + num + ", Current inventory:" + list.size () + "cannot continue to live                Production! ");                try {list.wait ();                } catch (Interruptedexception e) {e.printstacktrace ();                }} for (int i = 1; I <= num; ++i) {List.add (New Object ());            System.out.println ("Number of products produced:" + num + ", the current product volume is:" + list.size ());        } list.notifyall ();            }} public void consume (int num) {synchronized (list) {while (list.size () < num) {System.out.prinTLN ("The amount of products to be consumed:" + num + ", Inventory is:" + list.size () + ", insufficient stock, temporarily can not spend!");                try {list.wait ();                } catch (Interruptedexception e) {e.printstacktrace ();                }} for (int i = 1; I <= num; ++i) {list.remove ();            System.out.println ("Number of products consumed" + num + ", existing quantity:" + list.size ());        } list.notifyall ();    }}}public class Producer implements runnable{private int num;    Private Waitandnotify storage;    Public Producer (Waitandnotify storage) {this.storage = storage;    } public void Run () {produce (num);    } public void produce (int num) {storage.produce (num);    } public int Getnum () {return num;    } public void setnum (int num) {this.num = num; } public waitandnotify GetStorage () {RETurn storage;    } public void Setstorage (Waitandnotify storage) {this.storage = storage;    }}public class Consumer implements runnable{private int num;    Private Waitandnotify storage;    Public Consumer (Waitandnotify storage) {this.storage = storage;    } public void Run () {consume (num);    } public void consume (int num) {storage.consume (num);    } public int Getnum () {return num;    } public void setnum (int num) {this.num = num;    } public waitandnotify GetStorage () {return storage;    } public void Setstorage (Waitandnotify storage) {this.storage = storage; }}public class Waitandnotifytest {public static void main (string[] args) {waitandnotify storage = new WAITANDN        Otify ();        Producer P1 = new Producer (storage);        Producer P2 = new Producer (storage);        Producer p3 = new Producer (storage);        P1.setnum (10);        P2.setnum (20);P3.setnum (30);        Consumer C1 = new Consumer (storage);        Consumer C2 = new Consumer (storage);        C1.setnum (15);        C2.setnum (20);        P1.run ();        P2.run ();        C1.run ();        C2.run ();    P3.run (); }}

The results of the operation are as follows:

Number of products produced: 10, the current product volume is: 1 has produced the number of products: 10, the current product volume is: 2 produced Products: 10, the current product volume is: 3 Products: 10, the current product quantity is: 4 Products: 10, the product is: 5 has produced the number of products: 10, the product quantity is: 6 has produced the number of products : 10, the current product volume is: 7 products produced: 10, Current product Volume: 8 products produced: 10, Current product Volume: 9 Products: 10, current product Volume: 10 Products: 20, current product volume is: 11 products produced: 20, the current product volume is: 12 Production Products: 20, the The current product volume is: 13 has produced the number of products: 20, the current product volume is: 14 products produced: 20, the current product volume is: 15 Products: 20, the current product volume is: 16 Products: 20, the current product volume is: 17 products produced: 20, the current product volume is: 18 Production Products: 20, The current product volume is: 19 has produced the number of products: 20, the current product volume is: 20 products produced: 20, the current product volume is: 21 Products: 20, the current product volume is: 22 Products: 20, the current product volume is: 23 Products produced: 20, the current product volume is: 24 Production Products: 20, The current product volume is: 25 products produced: 20, the current product volume is: 26 Products produced: 20, the current product volume is: 27 Products: 20, the current product volume is: 28 Products: 20, the current product volume is: 29 products produced: 20, the current product volume is: 30 Consumer products Number 15, The existing quantity is: 29 Consumer Products Number 15, the existing volume is: 28 Consumer Products 15, the existing volume is: 27 of consumer Products is 15, the existing volume is: 26 of consumer Products is 15, the existing volume is: 25 of consumer products is 15, the current volume is: 24 of the consumption of products is 15, the existing quantity is : 23 of consumer Products 15, existing volume: 22 of Consumer Products 15, existing volume: 21 of consumer Products (15), existing volume: 20 of consumer Products (15), existing volume: 19 of consumer Products (15), existing volume: 18 of consumer Products (15), existing quantity: 17 of consumer Products 15, The existing volume is: 16 Consumer Products Number 15, the existing volume is: 15 to consume the volume of products: 20, Inventory is: 15, insufficient stock, temporarily can not spend!

Here's the question: Should you use notify or notifyall in order to wake up a waiting thread?

  In general, you should use Notifyall, which is a reasonable and conservative recommendation that always produces the correct result because it guarantees that all threads that need to be awakened will be awakened. Some other threads may be awakened, but this does not affect the correctness of the program, and these threads wake up to check the conditions they are waiting for, and if the condition is not satisfied, they will continue to wait.
  
From an optimization point of view, if all the threads in the waiting state are waiting for the same condition, and only one thread can be awakened from this condition at a time, then notify should be chosen instead of Notifyall.
  

2, Blockingqueue Method:

Using wait and notify directly is like programming with a "concurrent programming language", while Java.util.concurrent provides a more advanced language, and there is no reason to use wait and notify in new code. Even if there is, there are very few. Here we compare the blocking queue method Blockingqueue, which is the main tool under Java.util.concurrent to control thread synchronization.

public class blockingqueue{Private final int max_size = 100;    Private linkedblockingqueue<object> productlist = new linkedblockingqueue<object> (100); public void produce (int num) {if (productlist.size () = = max_size) {System.out.println ("Production stock        As: "+ max_size +", inventory is full, temporarily unable to produce! ");            for (int i = 1; I <= num; ++i) {try {productlist.put (New Object ());            } catch (Interruptedexception e) {e.printstacktrace ();        } System.out.println ("Production inventory:" + productlist.size ()); }} public void consume (int num) {if (productlist.size () = = 0) {System.out.println ("consumption        Stock is 0, temporarily cannot spend! "); for (int i = 1; I <= num; ++i) {if (productlist.size () < num) {System. Out.println ("Quantity of products to be consumed:" + num + ", Current inventory:" + ProductList.size () + ", insufficient stock, cannot consume!");            } try {productlist.take ();            } catch (Interruptedexception e) {e.printstacktrace ();    }} System.out.println ("Consumption stock:" + productlist.size ());    }}public class Producer implements Runnable {private int num;    Private Blockingqueue storage;    Public Producer (Blockingqueue storage) {this.storage = storage;    } public void Run () {produce (num); } public void produce (int num) {storage.    Produce (num);    } public int Getnum () {return num;    } public void setnum (int num) {this.num = num;    } public Blockingqueue GetStorage () {return storage;    } public void Setstorage (Blockingqueue storage) {this.storage = storage;    }}public class Consumer implements runnable{private int num;    Private Blockingqueue storage; Public Consumer (Blockingqueue storage) {this.storage = storage;    } public void Run () {consume (num); } public void consume (int num) {storage.    Consume (num);    } public int Getnum () {return num;    } public void setnum (int num) {this.num = num;    } public Blockingqueue GetStorage () {return storage;    } public void Setstorage (Blockingqueue storage) {this.storage = storage; }}public class Blockingqueuetest {public static void main (string[] args) {blockingqueue storage = new Blocking        Queue ();        Producer P1 = new Producer (storage);        Producer P2 = new Producer (storage);        Producer p3 = new Producer (storage);        P1.setnum (10);        P2.setnum (20);        P3.setnum (30);        Consumer C1 = new Consumer (storage);        Consumer C2 = new Consumer (storage);        C1.setnum (15);        C2.setnum (20);        P1.run ();        P2.run ();        C1.run ();        C2.run ();    P3.run (); }}

The results of the operation are as follows:

Production stock: 1 production stock: 2 production stock is: 3 Production stock: 4 Production Inventory: 5 Production Inventory: 6 Production Inventory: 7 Production Inventory: 8 Production Inventory: 9 in Production inventory: 10 production inventory as follows: 11 production inventory is of production stock is £ º : 13 Production Stock: 14 production stock is: 15 Production stock: 16 Production Inventory: 17 Production Inventory: 18 Production Inventory: 19 Production Inventory: 20 Production Inventory: 21 Production Inventory is: 22 production stock is: 23 production stock is production inventory is the following: 24 : 25 Production Stock: 26 Production Stock: 27 Production Inventory: 28 Production Inventory: 29 Production Inventory: 30 Consumption Stock: 15 of products to be consumed: 20, Stock is: 15, insufficient stock, can not be consumed! Volume of products to be consumed: 20, current stock: 14, insufficient stock , can not spend! The amount of products to be consumed: 20, Inventory is: 13, insufficient stock, can not be consumed! The quantity to be consumed: 20, Inventory is: 12, insufficient stock, can not consume! The quantity to be consumed: 20, Stock is: 11, insufficient stock, can not consume! Volume of products to be consumed: 20, Stock is now: 10, insufficient stock, can not be consumed! The quantity of products to be consumed: 20, Inventory is: 9, insufficient stock, can not be consumed! The quantity to be consumed: 20, the stock quantity is: 8, insufficient stock, cannot consume! The quantity to consume: 20, Stock quantity is: 7, insufficient stock, cannot consume! The amount of products to be consumed: 20, Stock is now: 6, insufficient stock, can not be consumed! The amount of products to be consumed: 20, Stock is now: 5, insufficient stock, can not be consumed! The amount of products to be consumed: 20, Stock is now: 4, insufficient stock, can not be consumed! Quantity of products to be consumed: 20, Current stock: 3, insufficient stock , can not spend! The amount of products to be consumed: 20, Inventory is: 2, insufficient stock, can not be consumed! The quantity to be consumed: 20, Inventory is: 1, insufficient stock, can not consume! The quantity of products to be consumed: 20, Stock quantity is: 0, insufficient stock, cannot consume!

  

 

  

Two ways to realize the model of producer and consumer

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.