Producer and consumer model

Source: Internet
Author: User

The producer and consumer modes are shown in.

Blog purpose: Use graphs to speak.


Sample Code:

Package COM. huan; public class produceconsumer {public static void main (string [] ARGs) {middleware = new middleware (); New thread (new producer (middleware )). start (); New thread (new consumer (middleware )). start () ;}} class producer implements runnable {private middleware; Public producer (middleware) {This. middleware = middleware;} public void produce () throws exception {While (true) {middleware. put () ;}@ overridepublic void run () {try {produce ();} catch (exception e) {e. printstacktrace () ;}} class Consumer implements runnable {private middleware; public consumer (middleware) {This. middleware = middleware;} public void consume () throws exception {While (true) {middleware. get () ;}@ overridepublic void run () {try {consume ();} catch (exception e) {e. printstacktrace () ;}} class middleware {Private Static final int max_size = 10; private int [] storage = new int [max_size]; private int Index = 0; public synchronized void put () throws exception {If (Index = max_size) {Wait ();} storage [Index] = index; system. out. println ("produced:" + index); index ++; Policy ();} public synchronized void get () throws exception {If (Index = 0) {Wait () ;}index --; system. out. println ("consumed:" + storage [Index]); Using Y ();}}

Code defect: when multiple consumers or multiple producers, the code of the above example needs to be improved.


Producer and 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.