Java completes producer consumer model

Source: Internet
Author: User

Producer and consumer models are typical models in multi-threading, where Java is used to complete the model

Servertest.java Producer Code

 PackageCom.orange.threadmodel;ImportJava.util.Queue; Public classServertestImplementsrunnable{PrivateQueue<string>queue;  PublicServertest (queue<string>queue) {         This. Queue =queue; } @Override Public voidrun () { while(true){            Try{                if(Queue.size () < 10) {System.out.println ("Generate Goods ..."); Queue.offer ("String-->"); Thread.Sleep (1000); }Else{System.out.println ("Unable to generate goods, inventory full"); Thread.Sleep (3000); }            }Catch(Exception e) {e.printstacktrace (); }        }    }        }

Clienttest.java Consumer Code

 PackageCom.orange.threadmodel;ImportJava.util.Queue; Public classClienttestImplementsrunnable{PrivateQueue<string>queue;  PublicClienttest (queue<string>queue) {         This. Queue =queue; } @Override Public voidrun () { while(true){                Try{                    if(Queue.isempty ()) {System.out.println ("The goods are consumed and no longer consumed ..."); Thread.Sleep (10000); }Else{System.out.println ("Consumer goods ...");                        Queue.poll (); Thread.Sleep (20000); }                }Catch(Exception e) {e.printstacktrace (); }            }        }}

Modelclient.java Test Model Code

 PackageCom.orange.threadmodel;ImportJava.util.Queue;ImportJava.util.concurrent.ArrayBlockingQueue; Public classmodelclient {Private Staticqueue<string> queue =NewArrayblockingqueue<string> (10);  Public Static voidMain (string[] args) {Servertest St=Newservertest (queue); Clienttest CT=Newclienttest (queue); Thread T1=NewThread (ST); Thread T2=NewThread (CT);        T1.start ();    T2.start (); }    }

Test results:

Java completes producer consumer model

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.