1 Packageproducer;2 3 Public classSyncstack {4 intIndex =0;5steamedbun[] Bunarr =NewSTEAMEDBUN[6];//only 6 elements can be placed in a stack.6 7 Public synchronized voidpush (Steamedbun bun)8 {9 while(Index >= bunarr.length)//waiting on full stackTen { OneBun.setindex (bunarr.length-1);//Fixed steamed bun number A Try { - This. Wait (); -}Catch(interruptedexception e) { the //TODO auto-generated Catch block - e.printstacktrace (); - } - } + //this.notify (); //called when a single thread - This. Notifyall ();//broadcast to all chefs + ABunarr[index] =Bun; atindex++; - } - - Public synchronizedsteamedbun pop () - { - while(Index ==0)//stack empty, no steamed bread when waiting for production in { - Try { to This. Wait (); +}Catch(interruptedexception e) { - //TODO auto-generated Catch block the e.printstacktrace (); * } $ }Panax Notoginseng This. Notify ();//notify the foodie there is steamed bread - theindex--; + returnBunarr[index]; A } the + -}
1 Packageproducer;2 3 Public classProducerImplementsrunnable{4Syncstack SS =NULL;5 intpId;6 PublicProducer (Syncstack SS,intpId) {7 This. SS =SS;8 This. PId =pId;9 }Ten One @Override A Public voidrun () { - //TODO auto-generated Method Stub - for(inti=0;i<10;i++) the { -Steamedbun bun =NewSteamedbun (ss.index,pid*1000+i); - Ss.push (bun); -SYSTEM.OUT.PRINTLN ("* * * * did" +bun); + - Try { + intIRandom = (int) (Math.random () *2000); A Thread.Sleep (irandom); at}Catch(interruptedexception e) { - //TODO auto-generated Catch block - e.printstacktrace (); - } - } - } in -}
1 Packageproducer;2 3 Public classConsumerImplementsrunnable{4 5Syncstack SS =NULL;6 PublicConsumer (syncstack ss)7 {8 This. SS =SS;9 }Ten One @Override A Public voidrun () { - //TODO auto-generated Method Stub - for(intI= 0;i<30;i++) the { -Steamedbun bun =Ss.pop (); -System.out.println ("Eat" +bun); - + Try { -Thread.Sleep ((int) (Math.random () * 1000)); +}Catch(interruptedexception e) { A //TODO auto-generated Catch block at e.printstacktrace (); - } - } - } - -}
1 Packageproducer;2 3 Public classSteamedbun {4 Private intID;5 Private intindex;6 PublicSteamedbun (intIndexintID) {7 This. ID =ID;8 This. index =index;9 }Ten One PublicString toString () A { - return"A steamed bun, is the basket in the first" + (index+1) + "steamed bread, number" +ID; - } the - Public voidSetindex (intindex) { - This. index =index; - } +}
1 Packageproducer;2 3 Public classTest {4 Public Static voidMain (string[] args) {5Syncstack SS =NewSyncstack ();6 7 //new 3 chefs and a foodie's thread8 NewThread (NewProducer (ss,1) . Start ();9 NewThread (NewProducer (ss,2) . Start ();Ten NewThread (NewProducer (ss,3) . Start (); One AConsumer Consumer =NewConsumer (ss); - NewThread (consumer). Start (); - } the}
Java multithreaded producer Consumer issues