Producers
1 ImportJava.util.Random;2 3 4 Public classProducerextendsThread {5 6 PrivateStorage<product>storage;7 8 PublicProducer (storage<product>storage) {9 This. Storage =storage;Ten } One A @Override - Public voidrun () { - produce (); the } - - Private voidProduce () { - while(true) { +Product Product =NewProduct (NewRandom (). Nextint (100)); - storage.enstorage (product); + } A } at - -}
View Code
Consumers
1 Public classConsumerextendsThread {2 3 PrivateStorage<product>storage;4 5 PublicConsumer (storage<product>storage) {6 This. Storage =storage;7 }8 9 @OverrideTen Public voidrun () { One consume (); A } - - Private voidconsume () { the while(true) { - storage.destorage (); - } - } + - +}
View Code
Products
1 /**2 * Products3 * 4 * @authorthief5 *6 */7 Public classProduct {8 9 Private intID;Ten One PublicProduct (intID) { A This. ID =ID; - } - the @Override - PublicString toString () { - return"Product:" +ID; - } + -}
View Code
Warehouse
1 Importjava.util.ArrayList;2 Importjava.util.List;3 4 /**5 * Warehouse6 * 7 * @authorthief8 *9 * @param<E>Ten */ One Public classStorage<e> { A - Privatelist<e> list =NewArraylist<e>(); - the /** - * Warehousing - * - * @parame + */ - Public voidEnstorage (e e) { + synchronized(list) { A while( This. Isfull ()) { at Try { -System.out.println ("Warehouse full"); - list.wait (); -}Catch(interruptedexception E1) { - e1.printstacktrace (); - } in } - List.add (e); toSystem.out.println (Thread.CurrentThread (). GetName () + "Production Products"); + Try { -Thread.Sleep (10); the}Catch(interruptedexception E1) { * e1.printstacktrace (); $ }Panax Notoginseng List.notifyall (); - } the } + A /** the * out of position + * - * @parame $ */ $ PublicE destorage () { - synchronized(list) { - while( This. IsEmpty ()) { the Try { -System.out.println ("Warehouse is empty");Wuyi list.wait (); the}Catch(interruptedexception E1) { - e1.printstacktrace (); Wu } - } AboutE e = list.get (0); $List.remove (0); -System.out.println (Thread.CurrentThread (). GetName () + "consumer Products"); - Try { -Thread.Sleep (1000); A}Catch(interruptedexception E1) { + e1.printstacktrace (); the } - List.notifyall (); $ returne; the } the } the the /** - * Determine if the current warehouse is empty in * the * @return the */ About Public BooleanIsEmpty () { the returnList.isEmpty (); the } the + /** - * Determine if the current warehouse is full the * Bayi * @return the */ the Public BooleanIsfull () { - returnList.size () = = 5; - } the the}
View Code
Test code
1 Public classTest {2 3 Public Static voidMain (string[] args) {4 5Storage<product> Storage =NewStorage<product>();6 7 NewProducer (storage). Start ();8 NewConsumer (storage). Start ();9 }Ten One}
Java code implementation of producer-consumer model