/*** Created by Damon on 7/25/16. * Producer Consumer Testing*/ Public classProducer_consumer_test3 {/*Knowledge points (The following knowledge points can be found by Baidu): 0. Understanding of producer Consumer models 1.wait notify usage 2.synchronized Usage 3. The difference between wait and sleep*/ Public Static voidMain (string[] args) {operation Operation=Newoperation (); NewThread (NewConsumerthread (operation)). Start (); NewThread (NewProducerthread (operation)). Start (); } Static classGood {/*** ID of the product*/ Public intID; PublicGood (intID) { This. ID =ID; } } Static classOperation {/*** The maximum amount of storage data in the warehouse*/ Static Final intMax_number = 10; good[] Goods=NewGood[max_number]; /*** Number of current warehouses*/ Private intCurrnumber = 0; Public synchronized voidProduce (good good) { while(Currnumber = =Max_number) { Try{System.out.println ("= = = Warehouse full of!!! Stop production, warehouse maximum capacity-->> "+max_number); Wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} Currnumber++; System.out.println ("= = = Production of a, warehouse maximum capacity-->>" +max_number+ ", of course, the number of warehouses-->>" +currnumber); Goods[currnumber-1] =good; Notify (); } Public synchronized voidconsume () { while(currnumber==0){ Try{System.out.println ("= = = The Warehouse is empty!!! Waiting in ... "); Wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} Currnumber--; Goods[currnumber]=NULL; System.out.println ("= = = Consume a!!! And the warehouse has "+currnumber+".); Notify (); } } /*** Threads for product production*/ Static classProducerthreadImplementsRunnable {Privateoperation Operation; Private intID; PublicProducerthread (Operation operation) { This. Operation =operation; } @Override Public voidrun () { while(true) { Try{operation.produce (NewGood (id)); ID++; Thread.Sleep (1000L); } Catch(interruptedexception e) {e.printstacktrace (); } } } } /*** Threads for consumer products*/ Static classConsumerthreadImplementsRunnable {Privateoperation Operation; PublicConsumerthread (Operation operation) { This. Operation =operation; } @Override Public voidrun () { while(true) { Try{operation.consume (); Thread.Sleep (2400L); } Catch(interruptedexception e) {e.printstacktrace (); } } } }}
Producer Consumer Model