Java multithreaded design pattern (2) producer and consumer models

Source: Internet
Author: User

1 Producer-consumer Pattern

Producer-consumer pattern is mainly to create a "bridge participant" between producer and consumer, to solve the mismatch between producer thread and consumer thread speed.

When you want to transfer data from a thread produccer a participant to another thread consumer the participant, you can add a channel participant in the middle, store the received information in some way in the channel participant, and then get the received data in a certain way, The channel can cache data transmitted between two threads, and in the channel participants to ensure security, also use guarded suspension pattern.

Channel participants as an intermediary, when a channel participant receives data from a producer participant, it is possible to pass the data sequentially to the consumer participant in three different ways.

1 queue, which stores data in a FIFO manner, that is, the first data that arrives is transmitted to the consumer participant first. In Java, it can be stored in an array form, each time it is fetched from the top of the array subscript, and the data is cached from the last end of the array subscript. LinkedList can also be used to store, each time the data is cached, the use of Linkedlist.addlast (obj), each time the data is obtained by the use of Linkedlist.removefirst (), remove and return the first element of the queue.

2 stack, which is a LIFO way of storing data, that is, the data that arrives first is finally transmitted to the consumer participant. In Java, for the implementation of the stack, you can use LinkedList to fetch data from the top of the stack using pop (), using push (obj) to cache a data in the stack

3 priority queues, which set some priority for the cached data to be stored.

The producer and consumer model, in fact, is the cooperative relationship between the threads, but also contains the mutually exclusive relationship. The so-called cooperation is the producer to produce products, to provide consumer consumption. The so-called mutex is that producers and consumers are mutually exclusive access to the intermediate buffers.

Instance:

Several cooks cook food and place the items on the table, but the table has a limited plate, and consumers can get food from the table. When there is a vacant position on the table, the chef can continue to place good food, and inform the consumer to eat, but full can only wait for the consumer to eat a vacant position. Every time the consumer takes food, if there is food on the table, then take away, and inform the chef to make food, if not then wait.

Producer Producer Code:

 PackageWhut.producer;ImportJava.util.Random; Public classMakerthreadextendsthread{Private Finaltable table; Private Finalrandom random; Private Static intId=0;  PublicMakerthread (String name,table Table,Longseed) {        Super(name);  This. table=table;  This. random=NewRandom (SEED); }                                                                             Public voidrun () {Try{             while(true) {Thread.Sleep (Random.nextint (1000)); String Cake= "[Cake No." +nextid () + "by" +thread.currentthread (). GetName () + "]";                                                                                                Table.put (cake); }        }Catch(Interruptedexception e) {}}//to make all instances share the field     Public Static synchronized intNextID () {returnid++; }}

Consumer Consumer Code:

 PackageWhut.producer;ImportJava.util.Random; Public classEaterthreadextendsthread{Private Finaltable table; Private Finalrandom random;  PublicEaterthread (String name,table Table,Longseed) {        Super(name);  This. table=table;  This. random=NewRandom (SEED); }     Public voidrun () {Try{             while(true) {String cake=Table.take (); Thread.Sleep (Random.nextint (1000)); }        }Catch(Interruptedexception e) {} }}

Channel Intermediate buffer, key part

Package Whut.producer;public class Table {private final string[] cakes;//takes advantage of an array as a buffer private int head;//The next cake take position pri vate int tail;//Next cake placement location private int count;//Total number of cakes on table public table (int count) {this.cakes=new String[cou        NT];        This.head=0;        this.tail=0;    this.count=0; } public synchronized void put (String cake) throws Interruptedexception {System.ou        T.println (Thread.CurrentThread (). GetName () + "puts" +cake);            while (count>=cakes.length) {System.out.println (Thread.CurrentThread (). GetName () + "Begin wait ...");            Wait ();        System.out.println (Thread.CurrentThread (). GetName () + "End wait ...");        } Cakes[tail]=cake;        Tail= (tail+1)%cakes.length;        count++;    Notifyall (); }//Fetch cake public synchronized String takes () throws Interruptedexception {while (CO unt<=0) {System.out.println (Thread.CurrentThread (). GetName () + "Begin wait ...");            Wait ();        System.out.println (Thread.CurrentThread (). GetName () + "End wait ...");        } String Cake=cakes[head];        Head= (head+1)%cakes.length;        count--;        Notifyall ();        System.out.println (Thread.CurrentThread (). GetName () + "gets" +cake);    return cake; }}

Test class:

 PackageWhut.producer; Public classMaintest { Public Static voidMain (string[] args) {//TODO auto-generated Method StubTable table=NewTable (3); NewMakerthread ("MakerThread-1", table,31415). Start (); NewMakerthread ("MakerThread-2", table,92653). Start (); NewMakerthread ("MakerThread-3", table,58979). Start (); NewEaterthread ("EaterThread-1", table,32384). Start (); NewEaterthread ("EaterThread-2", table,32384). Start (); NewEaterthread ("EaterThread-3", table,32384). Start (); //You can break end any thread by calling interrupt    }}

Java multithreaded design pattern (2) producer and consumer models

Related Article

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.