(One interview question) thread-producer consumer question, question producer

Source: Internet
Author: User

(One interview question) thread-producer consumer question, question producer

1. Question about producer and consumer?

1. Producer and consumer problems (English: Producer-consumer problem), also known as the limited buffer problem (English: Bounded-buffer problem), are a classic case of multi-thread synchronization problems. This problem describes two threads that share a fixed-size buffer-the so-called "producer" and "consumer"-problems that will occur during actual operation. The main function of the producer is to generate a certain amount of data into the buffer zone and repeat this process. At the same time, consumers consume the data in the buffer zone. The key to this problem is to ensure that the producer does not add data when the buffer zone is full, and the consumer does not consume data when the buffer zone is empty.

2. solution:

To solve this problem, the producer must sleep when the buffer zone is full (or simply discard the data) and wait until the next time the consumer consumes the data in the buffer zone, start adding data to the buffer. Similarly, the consumer can sleep when the buffer is empty, and then wake up the consumer after the producer adds data to the buffer. The problem is usually solved by means of inter-process communication. Common methods include the traffic signal method. If the solution is not complete, deadlocks may occur. When a deadlock occurs, both threads will sleep and wait for the other thread to wake up. This problem can also be promoted to multiple producers and consumers.

Ii. coding for producer consumers

1. First, let's see the result chart: I defined three producers: Zhang Fei, Zhao Yun, and Guan Yu, and Cao and Liu Bei.

First, the result is shown in the figure to illustrate that the multi-thread is to snatch cpu resources. Whoever gets it can execute its own method.

 

2. producer and consumer implementation steps:

(1) because the producer shares a region with the consumer, I define this region as a "warehouse ".

(2) The repository has a capacity limit. When the number reaches the upper limit, the producer cannot continue to produce the product. The current thread enters the waiting state and waits for other threads to wake up.

(3) When there is no product in the warehouse, the consumer is not allowed to continue consumption. The current thread enters the waiting state and waits for other threads to wake up.

3. Code implementation:

(1). Products are consumed between producers and consumers. All products are defined first:

Public class Product {// define the unique ID int id of the Product; // define the constructor to initialize the Product idpublic Product (int id) {this. id = id; // TODO Auto-generated constructor stub }}

(2) define a warehouse to store products.

Public class repermission{ // define a collection class to store the product. the maximum capacity of the specified warehouse is 10. public region list <Product> store = new region list <Product> (); public region list <Product> getStore () {return store;} public void setStore (region list <Product> store) {this. store = store;}/* producer Method * push () method used to store products. * parameter description: the first is the product object * The second is the thread name, which is used to show who produced the product. * purpose of modifying the method using the synchronized keyword: * a maximum of one thread can access this method at the same time. * The main purpose is to prevent multiple threads from accessing this method and overwrite the parameter data, causing an error. */public synchronized void push (Product p, String threadName) {/* The maximum warehouse capacity is 10. When the capacity is equal to 10, it enters the waiting state. wait for other threads to wake up * and then continue the cycle. When the inventory of the warehouse is less than 10, jump out of the loop and continue to run down to prepare the production product. */while (store. size () = 10) {try {// print the log System. out. println (threadName + "report: the Warehouse is full ---> enter the waiting status ---> call the boss to consume"); // unable to continue production because the warehouse capacity is full and enters the waiting status, wait for other threads to wake up. this. wait ();} catch (InterruptedException e) {e. printStackTrace () ;}// wake up all waiting threads this. yyall (); // Add the product to the repository. store. addLast (p); // print the Production Log System. out. println (threadName + "produced:" + p. id + "product" + "" + "current inventory:" + store. size (); try {// wait 0.1 seconds after each production to facilitate observation. thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace () ;}/ * Consumer Method * pop () is used to store products. * parameter description: thread name, used to show who produces the product. * purpose of modifying the method using the synchronized keyword: * a maximum of one thread can access this method at the same time. * The main purpose is to prevent multiple threads from accessing this method and overwrite the parameter data, causing an error. */public synchronized void pop (String threadName) {/* When the warehouse has no inventory, the consumer needs to wait. wait for other threads to wake up * and then continue the cycle. When the inventory of the warehouse is greater than 0, jump out of the loop and continue to execute the preparation for consumption products. */while (store. size () = 0) {try {// print the log System. out. println (threadName + "command: the Warehouse is empty ---> enter the waiting state ---> command younger brother to quickly produce"); // unable to continue consumption because the warehouse capacity is empty, enter the waiting state, wait for other threads to wake up. this. wait ();} catch (InterruptedException e) {e. printStackTrace () ;}// wake up all waiting threads this. policyall (); // store. the removeFirst () method removes the product from the warehouse. // print the log System. out. println (threadName + "consumed:" + store. removeFirst (). id + "product" + "" + "current inventory:" + store. size (); try {// wait 1 second after each production to facilitate observation. thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();}}}

(3). Define the producer

Public class Producer implements Runnable {// defines a static variable to record the number of products. ensure the uniqueness of each product. public static Integer count = 0; // defines the repository repermissionrepermission= null; // constructor initializes repermission( repository) public Producer (repermissionrepermission) {this. repermission= repermission;}/* run () method because the method contains non-atomic operation count ++; * multiple operations of count ++ occur when multiple threads access this method at the same time, resulting in an error. * Add synchronization errors for this method to ensure that only one producer can access this module at a time. * This ensures the security of the count ++ operation. * // @ Overridepublic void run () {while (true) {synchronized (Producer. class) {count ++; Product product = new Product (count); repertory. push (product, Thread. currentThread (). getName ());}}}}

(4) define a consumer

Public class Consumer implements Runnable {// defines repository repermissionrepermission= null; // constructor initializes repermission( repository) public Consumer (repermissionrepermission) {this. repertory = repertory;} // implement the run () method and pass in the name of the current thread. @ Overridepublic void run () {while (true) {repertory. pop (Thread. currentThread (). getName ());}}}

(5). Test class

Public class TestDemo {public static void main (String [] args) {// defines a repository. both consumers and producers use this repository repermissionrepermission= new repermission (); // define three producers (p1, p2, p3) Producer p1 = new Producer (repercer); Producer p2 = new Producer (repercer); Producer p3 = new Producer (repercer ); // define two consumers (c1, c2) Consumer c1 = new Consumer (repersumer); Consumer c2 = new Consumer (repersumer); // define five threads (t1, t2, t3, t4, t5) Thread t1 = new Thread (p1, "Zhang Fei"); Thread t2 = new Thread (p2, "Zhao Yun"); Thread t3 = new Thread (p3, "Guan Yu"); Thread t4 = new Thread (c1, "Liu Bei"); Thread t5 = new Thread (c2, "Cao "); // Since Guan Yu and Zhao Yun are highly active in production, increase their thread priority by a bit t2.setPriority (10); t3.setPriority (10); // start the thread t1.start (); t2.start (); t3.start (); t4.start (); t5.start ();}}

Iii. Summary:

I have made some tips for producer and consumer issues for several days. After I have finished this, I will post my own ideas. Thank you for your advice.

 

 

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.