Communication between threads (sell bread)

Source: Internet
Author: User

Package Mianbao;import java.util.Random; Public classTestbread {/** * @param args*/     Public Static voidMain (string[] args) {Store store=NewStore (); Maker m=NewMaker (store); Saler s=NewSaler (store);    M.start ();    S.start (); }}//Bakery Categoryclassstore{intnum=0;//the number of breadRandom r=NewRandom ();//Production of Bread PublicSynchronizedvoidMake () {if(num==0) {num=r.nextint ( -)+1; System. out. println ("A total of bread production is completed"+num); }//inform consumers to sell bread and block themselves     This. Notify (); Try {         This. Wait (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }//Selling Bread PublicSynchronizedvoidSale () {if(num>0){        intI=r.nextint (num) +1; System. out. println ("Sales of Bread:"+i); Num-=i; }Else{        //inform producers to produce bread         This. Notifyall ();//Same as Notify () in this program        Try {             This. Wait (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}    }//Producer ThreadsclassMaker extends thread{Store s;  PublicMaker (Store s) {super ();  This. S =s; }     Public voidrun () { while(true) {s.make (); Try{Thread.Sleep ( -); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }}classSaler extends thread{Store s;  PublicSaler (Store s) {super ();  This. S =s; }     Public voidrun () { while(true) {S.sale (); Try{Thread.Sleep ( -); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }}

Communication between threads (sell bread)

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.