Producers and consumers:
1 Public classProducerconsumer {2 Public Static voidMain (string[] args) {3Basket bs=Newbasket ();4Producer p=NewProducer (BS);5Consumer stu1=NewConsumer ("Zhang Dong", BS);6Consumer stu2=NewConsumer ("Wang Qiang", BS);7Consumer stu3=NewConsumer ("Zhao Lu", BS);8 NewThread (P). Start ();9 NewThread (STU1). Start ();Ten NewThread (STU2). Start (); One NewThread (STU3). Start (); A } - } - the classMantou { - intID; -Mantou (intID) { - This. id=ID; + } - PublicString toString () { + return"First" +id+ "Steamed bread" ; A } at } - - classBasket { - intindex = 0; -mantou[] Mt =NewMantou[10]; - in Public synchronized voidpush (Mantou ton) { - while(Index = =mt.length) { to Try { + This. Wait (); -}Catch(interruptedexception e) { the e.printstacktrace (); * } $ }Panax Notoginseng This. Notifyall (); -Mt[index] =ton; theindex++; + } A Public synchronizedMantou Pop () { the while(Index = = 0) { + Try { - This. Wait (); $}Catch(interruptedexception e) { $ e.printstacktrace (); - } - } the This. Notifyall (); -index--;Wuyi returnMt[index]; the } - Wu } - About classProducerImplementsrunnable{ $Basket bs=NULL; - Producer (Basket BS) { - This. bs=BS; - } A Public voidrun () { + for(inti=1;i<=15;i++){ theMantou mt=NewMantou (i); - Bs.push (MT); $System.out.println ("Master Li produced" +mt.tostring ()); the Try{ theThread.Sleep ((int) (Math.random () *100)); the}Catch(interruptedexception e) { the e.printstacktrace (); - } in } the } the About } the the the classConsumerImplementsrunnable{ +Basket bs=NULL; - String name; the Consumer (String stu,basket bs) {Bayi This. bs=BS; theName=Stu; the } - Public voidrun () { - for(inti=1;i<=5;i++){ theMantou mt=Bs.pop (); theSystem.out.println (name+ "consumed" +mt.tostring ()); the Try{ theThread.Sleep ((int) (Math.random () *1000)); -}Catch(interruptedexception e) { the e.printstacktrace (); the } the }94 } the the}View Code
Java Routine Practice