Solve the concurrent problem of java producer consumer, java producer

Source: Internet
Author: User

Solve the concurrent problem of java producer consumer, java producer

Introduction

The producer and consumer problems are classic issues in the thread model:Same timeSegmentIntranet sharingSame bucketAs shown in, if the producer stores data into the space and the consumer uses the data, the following situations may occur if the data is not coordinated:

Producer consumer Diagram

The storage space is full, and the producer occupies it. The consumer waits for the producer to let out the space to remove the product. The producer waits for the consumer to consume the product and then adds the product to the space. Wait for each other and thenDeadlock.

The producer consumer problem is one of the classic problems that cannot be circumvented when a multi-threaded program is studied. It describes that a buffer zone is used as a warehouse, and the producer can put the product into a warehouse, consumers can remove products from the warehouse. There are two solutions to producer/consumer problems:

(1) adopt a mechanism to protect synchronization between producers and consumers;

(2) establish a pipeline between producers and consumers.

The first method is highly efficient and easy to implement. It provides better code control and is a common mode. The second method is difficult to control the MPs queue buffer, and the transmitted data objects are not easy to encapsulate. This method is not practical. Therefore, this article only describes the producer/consumer issues implemented by the synchronization mechanism.

SynchronizationCore issuesIt is about how to ensure the integrity of the same resource when it is accessed by multiple threads concurrently. A common synchronization method is to use a signal or locking mechanism to ensure that resources are accessed by at most one thread at any time. The Java language is fully object-oriented in multi-threaded programming and provides good support for synchronization mechanisms. There are four methods in Java that support synchronization. The first three are synchronous methods, and the other is the pipeline method.

(1) wait ()/notify () method

(2) await ()/signal () method

(3) BlockingQueue blocking queue Method

(4) PipedInputStream/PipedOutputStream

This article only describes the first two most commonly used methods. The third and fourth types are not discussed for the moment. Interested readers can find their answers online.

 

I,Wait ()/notify ()Method

The wait ()/nofity () method is the two methods of the base class Object, which means that all Java classes will have these two methods, so that we can implement a synchronization mechanism for any Object.

  Wait () method: When the buffer zone is full or empty, the producer/consumer thread stops its execution, gives up the lock, and puts itself in a waiting state for other threads to execute.

  Y () method: When the producer/consumer puts/fetches a product from the buffer zone, it sends an executable notification to other waiting threads and gives up the lock to keep itself in the waiting state.

 

Code implementation:

1. Warehouse

Import java. util. repository list;/*** repository class Storage implementation buffer ** @ author zcr */public class Storage {// maximum repository Storage private final int MAX_SIZE = 100; // The carrier private objects list <Object> list = new objects list <Object> (); /*** number of production products for num * @ param num */public void produce (int num) {// Synchronous Code segment synchronized (list) {// if the remaining warehouse capacity is insufficient while (list. size () + num> MAX_SIZE) {System. out. println ("[number of products to be produced]:" + num + "\ T [inventory]:" + list. size () + "\ t cannot execute production tasks for the moment! "); Try {// The Production Blocking list due to the condition is not met. wait ();} catch (InterruptedException e) {e. printStackTrace () ;}/// when the production conditions are met, generate num products for (int I = 1; I <= num; ++ I) {list. add (new Object ();} System. out. println ("[number of products already produced]:" + num + "\ t [current storage volume]:" + list. size (); list. notifyAll () ;}}/*** consume num products * @ param num Number of consumed products */public void consume (int num) {// Synchronous Code segment synchronized (list) {// If the warehouse storage is insufficient while (list. size () <Num) {System. out. println ("[number of products to be consumed]:" + num + "\ t [inventory]:" + list. size () + "\ t cannot execute production tasks now! "); Try {// consumption blocking list due to the condition not met. wait ();} catch (InterruptedException e) {e. printStackTrace () ;}/// when the consumption conditions are met, the consumption of num products for (int I = 1; I <= num; ++ I) {list. remove ();} System. out. println ("[number of consumed products]:" + num + "\ t [current storage volume]:" + list. size (); list. policyall () ;}/// get/set Method public writable list <Object> getList () {return list;} public void setList (writable list <Object> list) {this. list = list;} public int getMAX_SIZE () {return MAX_SIZE ;}}

 

2. Producer

/*** Producer class Producer inherits Thread class Thread *** @ author zcr **/public class Producer extends Thread {// number of products produced each time private int num; // private Storage storage in the repository; // constructor, set public Producer (Storage storage Storage) {this. storage = storage;} // The thread run function public void run () {produce (num);} // call the production function public void produce (int num) {Storage. produce (num);} // get/set Method public int getNum () {return num;} public void setNum (int num) {this. num = num;} public Storage getStorage () {return storage;} public void setStorage (Storage storage) {this. storage = storage ;}}

 

 

3. Consumers

/*** Consumer class Consumer inherits Thread class *** @ author zcr ***/public class Consumer extends Thread {// number of products consumed each time private int num; // private Storage storage in the repository; // constructor, set public Consumer (Storage storage Storage) {this. storage = storage;} // The thread run function public void run () {consume (num);} // call the production function public void consume (int num) {Storage. consume (num);} // get/set Method public int getNum () {return num;} public void setNum (int num) {this. num = num;} public Storage getStorage () {return storage;} public void setStorage (Storage storage) {this. storage = storage ;}}

 

 

4. Testing

/*** Test class * @ author zcr **/public class Test {public static void main (String [] args) {// repository Object Storage storage = new Storage (); // Producer object: Producer p1 = new Producer (storage); Producer p2 = new Producer (storage); Producer p3 = new Producer (storage); Producer p4 = new Producer (storage ); producer p5 = new Producer (storage); Producer p6 = new Producer (storage); Producer p7 = new Producer (storage); // Consumer object Consumer c1 = new Consumer (storage ); consumer c2 = new Consumer (storage); Consumer c3 = new Consumer (storage); // set the production quantity of the producer product p1.setNum (10); p2.setNum (10); p3.setNum (10 ); p4.setNum (10); p5.setNum (10); p6.setNum (10); p7.setNum (80); // set the consumption quantity of the consumer product c1.setNum (50); c2.setNum (20 ); c3.setNum (30); // The thread starts to execute c1.start (); c2.start (); c3.start (); p1.start (); p2.start (); p3.start (); p4.start (); p5.start (); p6.start (); p7.start ();}}

 

 

5. Results:

[Number of products to be consumed]: 50 [inventory]: 0. production tasks cannot be executed temporarily! [Number of products to be consumed]: 20 [inventory]: 0. production tasks cannot be executed temporarily! [Number of products already produced]: 10 [current storage volume]: 10 [number of products to be consumed]: 20 [inventory volume]: 10 cannot execute production tasks temporarily! [Number of products to be consumed]: 50 [inventory]: 10 production tasks cannot be executed temporarily! [Number of products already produced]: 10 [current storage volume]: 20 [number of products already produced]: 10 [current storage volume]: 30 [number of products to be consumed ]: 50 [inventory]: 30 production tasks cannot be executed now! [Number of products consumed]: 20 [current storage volume]: 10 [number of products already produced]: 10 [current storage volume]: 20 [number of products already produced ]: 10 [current storage volume]: 30 [number of products to be consumed]: 50 [inventory volume]: 30 production tasks cannot be executed temporarily! [Number of products produced]: 10 [current storage volume]: 40 [number of products consumed]: 30 [current storage volume]: 10 [number of products to be consumed ]: 50 [inventory]: 10 production tasks cannot be executed now! [Number of products produced]: 80 [current storage volume]: 90 [number of products consumed]: 50 [current storage volume]: 40

 

After reading the above code, I learned about the synchronization of the wait ()/notify () method. You may be puzzled by the Storage class's definition of public void produce (int num); and public void consume (int num); method, why do we need to call the implementation in the Storage class instead of directly implementing these two methods in the Producer class Producer and Consumer class Consumer? Calm down, which will be explained later. Let's go down first.

 

 

II,Await ()/signal ()Method

After JDK5.0, Java provides a more robust thread processing mechanism, including synchronization, locking, and thread pool, which can implement more fine-grained thread control. Await () and signal () are two methods used for synchronization. Their functions are basically the same as those of wait ()/nofity (), but they can be replacedNew locking mechanism Lock direct hookWith greater flexibility. By locking an objectCall the newCondition () method to bind a condition variable to a lock object to control the security of concurrent programs accessing competing resources..

Let's look at the code below:

  OnlyYesUpdate repository classStorage codeNo changes are required for the Producer, Consumer, and Test code.

Warehouse

Import java. util. using list; import java. util. concurrent. locks. condition; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. reentrantLock;/*** repository-class Storage implements the buffer *** @ author MONKEY. d. MENG **/public class Storage {// maximum repository Storage private final int MAX_SIZE = 100; // private repository list of the carrier stored in the repository <Object> list = new repository list <Object> (); // Lock private final lock Lock = new Reen TrantLock (); // Condition variable private final Condition full = lock when the Warehouse is full. newCondition (); // The Condition variable private final Condition empty = lock. newCondition (); // generate num products public void produce (int num) {// obtain lock. lock (); // if the remaining warehouse capacity is insufficient while (list. size () + num> MAX_SIZE) {System. out. println ("[number of products to be produced]:" + num + "/t [inventory]:" + list. size () + "/t cannot execute production tasks for the moment! "); Try {// The production is blocked for full because the conditions are not met. await ();} catch (InterruptedException e) {e. printStackTrace () ;}/// when the production conditions are met, generate num products for (int I = 1; I <= num; ++ I) {list. add (new Object ();} System. out. println ("[number of products already produced]:" + num + "/t [current storage volume]:" + list. size (); // wake up all other threads to full. signalAll (); empty. signalAll (); // release the lock. unlock ();} // consume num products public void consume (int num) {// obtain lock. lock (); // If the warehouse storage volume is insufficient wh Ile (list. size () <num) {System. out. println ("[number of products to be consumed]:" + num + "/t [inventory]:" + list. size () + "/t cannot execute production tasks for the moment! "); Try {// consumption blocking empty because the conditions are not met. await ();} catch (InterruptedException e) {e. printStackTrace () ;}/// when the consumption conditions are met, the consumption of num products for (int I = 1; I <= num; ++ I) {list. remove ();} System. out. println ("[number of consumed products]:" + num + "/t [current storage volume]:" + list. size (); // wake up all other threads to full. signalAll (); empty. signalAll (); // release the lock. unlock ();} // set/get method public int getMAX_SIZE () {return MAX_SIZE;} public writable list <Object> getList () {return list ;} public void setList (empty list <Object> list) {this. list = list ;}}

 

 

Result:

[Number of products to be consumed]: 50/t [inventory]: 0/t production tasks cannot be executed temporarily! [Number of products already produced]: 10/t [current storage volume]: 10 [number of products already produced]: 10/t [current storage volume ]: 20 [number of products to be consumed]: 30/t [inventory]: 20/t production tasks cannot be executed temporarily! [Number of products consumed]: 20/t [current storage volume]: 0 [number of products produced]: 10/t [current storage volume ]: 10 [number of products already produced]: 10/t [current storage volume]: 20 [number of products to be consumed]: 50/t [inventory ]: 20/t cannot execute production tasks now! [Number of products already produced]: 10/t [current storage volume]: 30 [number of products already produced]: 10/t [current storage volume ]: 40 [number of products to be produced]: 80/t [inventory]: 40/t production tasks cannot be executed temporarily! [Number of products consumed]: 30/t [current storage volume]: 10 [number of products to be consumed]: 50/t [inventory ]: 10/t cannot execute production tasks now! [Number of products already produced]: 80/t [current storage volume]: 90 [number of products already consumed]: 50/t [current storage volume]: 40

 

  

In this way, we will know that for Shenma, I want to define public void produce (int num); and public void consume (int num) in the Storage class; method, the Producer class and Consumer class Consumer call the implementation in the Storage class. The possible changes are concentrated in one class, without affecting the original architecture design, and without modifying other business layer code.

 

 

Summary

The two methods are the same in principle. They are used to lock, block, and wake up the exclusive space. The first method is more traditional, and the second method is faster.

 

Thank you! Thank you for your patience!

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.