Welcome to Concurrency King Lessons, the 10th article in a series.

In this article, I’ll introduce you to the classic concurrency problem, the producer vs. consumer problem, and implement a simplified version of this problem using wait and notify, based on the previous articles.

First, the problem of producers and consumers

Producer-consumer problem, also known as Bounded-buffer problem, is a classic case of multi-process and thread synchronization problem.

This problem describes what happens when two processes that share a fixed-size buffer — so-called “producers” and “consumers” — actually run. The main role of the producer is to generate a certain amount of data into the buffer and then repeat the process. At the same time, consumers consume this data in the buffer.

The key to the producer-consumer problem is to ensure that the producer does not add data when the buffer is full, and the consumer does not consume data when the buffer is empty.

To solve this problem, you have to let the producer sleep until the buffer is full (or give up the data altogether) and wait until the next time the consumer consumes the data in the buffer, the producer can be woken up and start adding data to the buffer.

Similarly, you can put the consumer to sleep while the buffer is empty and then wake the consumer up after the producer has added data to the buffer. The method of communication between threads is usually used to solve this problem. The common methods include semaphore and so on. If the solution is not perfect, deadlock situations are likely to occur. When a deadlock occurs, both threads go to sleep and wait for the other to wake them up.

Of course, the problem of producer and consumer is not limited to a single producer and consumer. In practical work, we encounter more situations of multiple producers and consumers.

Producer and consumer model is widely used in software development and design. In this mode, producers and consumers are independent of each other, and they only pass data through buffers, so they can be used for decoupling between programs, asynchronous peak clipping, etc.

Key points of producer and consumer issues:

  • Producers and consumers are decoupled and both pass data through buffers.
  • When the buffer is full, the producer stops data production or discards data;
  • When the buffer data is empty, the consumer stops consumption and enters the wait state, waiting for the producer notification.

Second, the realization of producer and consumer programs

In this section, we simulate the producer-consumer problem through a scenario in King.

In the king, the hero lanling king needs to be hit by the wild to develop, but the wild monster in the wild area after being hit, need to be put into the field after a period of time.

So, we create two threads, one as a producer to throw monsters into the wild and one as a consumer to kill them.

Producer: check the wild area once a second. If there is no wild monster in the wild area, put it into the field. Wild monster put into the notice to play wild hero.

Public static class wildmonsterProducer implements Runnable {public void run() {try {} createWildMonster(); } catch (interruptedException e) {System.out.println(interruptedException e); Public void createWildMonster() throws InterruptedException {for (int I = 0;; I ++) {synchronized(wildmonsterArea) {if (wildmonsterArea. size() == 0) {wildmonsterArea. add(" "+ I); System.out.println(wildMonsterArea.getLast()); wildMonsterArea.notify(); } } Thread.sleep(1000); }}}

Consumer: fighting wild hero Lan Ling King as a consumer, in the wild area to fight the development of monsters. If there are wild monsters in the wild area, kill them. If not, it will wait for a new monster to spawn in the field.

Public static class LanlingWang implements Runnable {public void run() {try {attackWildMonster(); } catch (interruptedException e) {System.out.println(interruptedException e);} interrupt (interruptedException e) {System.out.println(interruptedException e); }} // play the field, Public void attackWildMonster() throws InterruptedException {while (true) {synchronized(WildMonsterArea) { if (wildMonsterArea.size() == 0) { wildMonsterArea.wait(); } String wildMonster = wildMonsterArea.getLast(); wildMonsterArea.remove(wildMonster); Println (" wildMonster: "+ wildMonster); }}}}

Create wild areas and start producer and consumer threads.

Public class ProducerConsumerProblemDemo {/ / creeps activity of wild area private static final LinkedList < String > wildMonsterArea = new LinkedList<String>(); public static void main(String[] args) { Thread wildMonsterProducerThread = new Thread(new WildMonsterProducer()); Thread lanLingWangThread = new Thread(new LanLingWang()); wildMonsterProducerThread.start(); lanLingWangThread.start(); }}

In the above code, you need to focus on the synchronized, wait, and notify usages, which are the key to this solution. The running results are as follows:

Wild Monster 0 Harvest Monster: Wild Monster 1 Wild Monster 2 Harvest Monster: Wild Monster 2 Wild Monster 3 Harvest Monster: Wild Monster 3 Wild Monster 4 Wild Monster 5 Harvest Monster 5 Wild Monster 6 Harvest Monster 6

As can be seen from the results, after the creation of wild monster, the hero of wild fighting, the king of lanling, will fight the wild, which realizes the problem of producer and consumer.

summary

That’s all for thread exception handling. In this article we solve producer and consumer issues based on wait and notify. For the purposes of this article, you need to understand what is at the heart of the producer versus consumer issue. In addition, the solution presented in this article is only one of several solutions to this problem, and we will provide other solutions based on new knowledge points in subsequent articles.

The text ends here, congratulations you went up a star ✨ again

Teacher’s trial

  • Write code to implement the producer versus consumer problem.

read

  • Producer – consumer problem
  • “Concurrent king lesson” outline and update progress overview

About the author

Pay attention to the public number [mediocre technology joke], access to timely article updates. Record the technical stories of ordinary people, share quality (as much as possible) technical articles, and occasionally talk about life and ideals. No anxiety peddling, no headline peddling.

If this article is helpful to you, welcome thumb up, follow, monitor, we together from bronze to king.