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)