Producer and consumer problems

Source: Internet
Author: User

**************************************** ******************************************************

Original works, from the "Xiaofeng residual month XJ" blog, welcome to reprint, reprint please be sure to indicate the source (http://blog.csdn.net/xiaofengcanyuexj ).

For various reasons, there may be many shortcomings. Thank you!

******************************************************* **************************************** **********

In the process of multi-threaded programming, synchronization and mutex between threads are the key points to be carefully considered. Producers and consumers are typical examples of synchronization between threads: several producers produce products, and several consumers consume these items at the same time, ensure that multiple producers and consumers can execute concurrently or concurrently (for the difference between parallelism and concurrency and some basic concepts of multithreading programming, refer to this blog post: multithreading preliminary. A typical solution for producers and consumers is to set up a product buffer, and multiple producers and consumers access the buffer mutex.

1. Model Analysis

The producer and consumer issues are essentially a synchronization and mutex problem. The following points should be noted:

1) Synchronization: When the buffer zone is not full, the producer thread can continue to execute. The producer execution result is to add products to the buffer zone. If the buffer zone is not empty, the consumer thread can continue to execute, the result of execution by the consumer is to retrieve the product from the buffer zone. Producers and consumers can execute each other to improve system efficiency and restore the authenticity of scenarios.

2) mutex: because both producers and consumers can change the status of the buffer zone, operations on the buffer zone should be mutually exclusive, that is, the same variables cannot be read at the same time to avoid read/write conflicts.

The buffer size setting and the number of producers and consumers affect the difficulty of this problem. For the sake of simplicity, it is assumed that the producer and consumer operate the products in the buffer zone in sequence.

2. Source Code

Import Java. util. arraylist; import Java. util. list; Class productbuffer {private list <integer> m_listproduct = new arraylist <integer> (); Private int m_nsize; Public productbuffer (INT size) {m_nsize = size; m_listproduct.clear ();} synchronized int get () {While (m_listproduct.size () <= 0) {try {Wait ();} catch (interruptedexception e) {system. out. println (e) ;}} int retvalue = m_listproduct.get (m_listproduct.size ()-1); m_listproduct.remove (m_listproduct.size ()-1); policyall (); Return retvalue ;} synchronized void put (INT Mon) {While (m_listproduct.size () >=m_nsize) {try {Wait ();} catch (interruptedexception e) {system. out. println (e) ;}}m_listproduct.add (Mon); policyall () ;}} class producer extends thread {private productbuffer m_product; private int m_nvalue; Producer (productbuffer pro, int value) {m_product = pro; m_nvalue = value;} public void run () {m_product.put (m_nvalue); system. out. println ("product in producer is" + m_nvalue); try {sleep (100);} catch (interruptedexception e) {system. out. println (e) ;}} class Consumer extends thread {private productbuffer m_product; Consumer (productbuffer Pro) {m_product = pro;} public void run () {int val = m_product.get (); system. out. println ("product in consumer is" + val) ;}} public class producerandconsumer {public static void main (string [] AGR) {productbuffer pro = new productbuffer (10 ); producer [] mypro = new producer [10]; for (INT I = 0; I <10; ++ I) {mypro [I] = new producer (Pro, i);} consumer [] mycon = new consumer [10]; for (INT I = 0; I <10; ++ I) {mycon [I] = new consumer (Pro) ;}for (INT I = 0; I <10; ++ I) {mypro [I]. start (); mycon [I]. start ();}}}
The code above achieves synchronization and mutex between multiple producers and multiple consumers. However, different producers and producers, producers and consumers, and consumers access the buffer zone at the same time, this is different from the readers and writers.

3. Notes

1) Java collections can only store reference data types and cannot store basic data types. Therefore, the following code snippet is wrong:

private List<int> m_listProduct = new ArrayList<int>();

It should be:

private List<Integer>  m_listProduct = new ArrayList<Integer>();

2) Use of synchronized

Synchronized can be used to lock an object or a method and declare that only one thread can access a code block or method modified by it at any time, in addition, the thread can access the code block or method not declared as synchronized. In Java, not only can the class instance object be modified with synchronized, but the class itself also corresponds to a lock with the modified synchronized, that is, the static member function of the class is declared as synchronized, to control its access to static member variables of the class. Defects of the Synchronized Method: declaring a large method as synchronized will greatly affect efficiency. You can minimize the scope of synchronized modified code segments to improve efficiency.

3) Use of wait () and policyall () Methods

In Java, policyall and wait Methods inherit from the base class objects shared by all classes.

A. Wait ()

This causes the current thread to wait until other threads call the notify () method or the notifyall () method of this object.

B. policyall ()

Wake up all threads waiting on this object monitor. By calling one of the threadswaitMethod, waiting on the object's monitor.

A. Some synchronized locations do not necessarily have wait (), Policy ()
B. Synchronized must exist in the wait () and notify () fields. Because wait () and notify () do not belong to the Thread class, but each object has a method. Moreover, these two methods are related to the object lock. Where there is a lock, there must be synchronized.


Due to limited time, I have referenced some documents during the blog writing process and would like to express my gratitude. In addition, you may have some shortcomings due to the level. Thank you!


Producer and consumer problems

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.