Java Producer Consumer Model

Source: Internet
Author: User

Why use producer and consumer models

In the world of threads, the producer is the thread of production data, and the consumer is the thread of consumption data. In multithreaded development, producers have to wait for the consumer to continue producing data if the producer is processing fast and the consumer processing is slow. Similarly, consumers must wait for producers if their processing power is greater than that of producers. In order to solve the problem of unbalanced production and consumption capacity, we have a model of producer and consumer.

What is the producer consumer model

The producer-consumer model solves the problem of strong coupling between producers and consumers through a container. Producers and consumers do not communicate with each other directly, and through the blocking queue to communicate, so producers do not have to wait for consumer processing after the production of data, directly to the blocking queue, consumers do not find producers to data, but directly from the blocking queue, the blocking queue is equivalent to a buffer, Balance the processing power of producers and consumers.

This blocking queue is used to decouple producers and consumers. Throughout most design patterns, a third party is found to decouple, such as the factory model of the third party is the factory class, template mode of the third party is a template class.

Producer Consumer model Combat

Using Blockingqueue

Package Com;import Java.util.random;import Java.util.concurrent.blockingqueue;public class Comsumer implements Runnable   {Private blockingqueue<pcdata> queue;private static final int sleeptime = 1000;public Comsumer ( Blockingqueue<pcdata> queue) {this.queue = queue;} @Overridepublic void Run () {System.out.println ("Start Consumer Id:" +thread.currentthread (). GetId ()); Random r = new Random (); Boolean isrunning = true;try {while (isrunning) {PCData data = Queue.take (), if (data! = null) {System.out.println ("Comsumer Data: "+data"); Thread.Sleep (R.nextint (Sleeptime));}} catch (Interruptedexception e) {e.printstacktrace ();            Thread.CurrentThread (). interrupt ();}}}

  

Package Com;import Java.util.random;import Java.util.concurrent.blockingqueue;import java.util.concurrent.TimeUnit ; Import Java.util.concurrent.atomic.atomicinteger;public class Producer implements Runnable{private volatile Boolean isrunning = true;//Memory buffer private blockingqueue<pcdata> queue;//Total atomicintegerprivate static Atomicinteger count = new Atomicinteger ();p rivate static final int sleeptime = 1000;public Producer (blockingqueue<pcdata> queue) { This.queue = queue;} public void Run () {PCData data = null; Random r = new Random (); System.out.println ("Start producting ID:" + thread.currentthread (). GetId ()); while (isrunning) {try {while (isrunning) { Thread.Sleep (R.nextint (sleeptime));d ata = new PCData (Count.incrementandget ()); if (!queue.offer (data,2), Timeunit.seconds)) {System.out.println ("Failed to join queue");} Else{system.out.println ("Producer data:" +data);}} catch (Interruptedexception e) {e.printstacktrace (); Thread.CurrentThread (). interrupt ();}}} public void Stop () {isrunning = false;}}

  

Package Com;public class PCData {private final int intdata;public PCData (int d) {intdata = D;} Public PCData (String d) {intdata = integer.valueof (d);} public int GetData () {return intdata;} @Overridepublic String toString () {return "" +intdata;}}

  

Package Com;import Java.util.concurrent.blockingqueue;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.linkedblockingqueue;public class Main {public static void Main (string[] args) throws interruptedexception{blockingqueue<pcdata> queue = new Linkedblockingqueue<> ( 10); Producer P1 = new Producer (queue); Producer P2 = new Producer (queue); Producer p3 = new Producer (queue); Comsumer C1 = new Comsumer (queue); Comsumer C2 = new Comsumer (queue); Comsumer C3 = new Comsumer (queue); Executorservice service = Executors.newcachedthreadpool (); Service.execute (p1); Service.execute (p2); Service.execute (p3); Service.execute (C1); Service.execute (C2); Service.execute (C3); Thread.Sleep (10*1000);p 1.stop ();p 2.stop ();p 3.stop (); Thread.Sleep (+); Service.shutdown ();}}

Using Notifyall and wait

Package Com;import Java.util.list;public class Consumer implements Runnable{private list<pcdata> Queue;public  Consumer (list<pcdata> queue) {this.queue = queue;} @Overridepublic void Run () {while (true) {PCData data = null;try {synchronized (queue) {if (queue.size () = = 0) {SYSTEM.OUT.PR Intln (Thread.CurrentThread (). GetId () + "queue is empty, cannot be consumed"); Queue.notifyall (); queue.wait ();} Else{data = queue.remove (0); System.out.println (Thread.CurrentThread (). GetId () + "consumption:" +data);} Thread.Sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();}}}}

  

Package Com;import Java.util.list;import Java.util.random;public class Producer implements Runnable {private list< pcdata> queue;private int length;public Producer (list<pcdata> queue,int length) {this.queue = queue; this.length = length;} @Overridepublic void Run () {while (true) {           random r = new Random (); PCData data = new PCData (r.nextint); try {synchronized (queue) {if (queue.size () >= length) {System.out.println ( Thread.CurrentThread (). GetId () + "queue full, unable to join"); Queue.notifyall (); queue.wait ();} Else{queue.add (data); System.out.println (Thread.CurrentThread (). GetId () + "produced:" +data);} Thread.Sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();}}}}

  

Package Com;import Java.util.arraylist;import Java.util.list;import java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class Main {public static void Main (string[] args) {list<pcdata> queue = new A Rraylist<> (); int length = 10; Producer P1 = new Producer (queue, length); Producer P2 = new Producer (queue, length); Producer p3 = new Producer (queue, length); Consumer C1 = new Consumer (queue); Consumer C2 = new Consumer (queue); Consumer C3 = new Consumer (queue); Executorservice service = Executors.newcachedthreadpool (); Service.execute (p1); Service.execute (p2); Service.execute (p3); Service.execute (C1); Service.execute (C2); Service.execute (C3);}}

  

Java Producer Consumer Model

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.