Producers to produce steamed bread, consumer consumption of steamed bread. A basket, the producer puts the steamed bread in the basket, the consumer takes the steamed bread from the basket.
/*** This is a basket class * *@authorXCX * @time July 21, 2017 morning 10:01:32*/ Public classBasket {//you can pack up to 10 buns in a basket. Private Final intMax_numbers_streamedbread = 10; Steamedbread[] Sbbreads=NewSteamedbread[max_numbers_streamedbread]; //used to mark the amount of steamed bread in a basket Private intindex = 0; //the method of putting steamed bread into the basket Public synchronized voidpush (Steamedbread sbbread) { while(Index >=max_numbers_streamedbread) { Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } This. Notify (); Sbbreads[index]=Sbbread; Index++; } //the way to take the steamed bread from the basket Public synchronizedsteamedbread Pop () { while(Index <= 0) { Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } return NULL; } This. Notify (); Index--; returnSbbreads[index]; }}
/*** Consumer class *@authorXCX * @time July 21, 2017 morning 10:23:53*/ Public classConsumerImplementsRunnable {Basket B=NewBasket (); PrivateSteamedbread Steamedbread; PublicConsumer (Basket b) { This. B =b; } @Override Public voidrun () { for(inti=0;i<20;i++) {Steamedbread=B.pop (); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } if(Steamedbread = =NULL){ }Else{System.out.println ("Consumption" +steamedbread); } } }}
/*** This is a producer class * *@authorXCX * @time July 21, 2017 morning 10:16:25*/ Public classProducerImplementsRunnable {PrivateBasket B =NewBasket (); PublicProducer (Basket b) { This. B =b; } @Override Public voidrun () { for(inti=0;i<20;i++) {Steamedbread Sbread=NewSteamedbread (i); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("The production of the first" +i+ "Steamed bread"); B.push (Sbread); } }}
/** *this is a class about Steamedbread * @author XCX * @time July 21, 2017 9:59:16 */ public Class Steamedbread { private int I; public steamedbread (int i) { this . I = I; @Override public String toString () { return "+i+" steamed bun "; }}
/*** Synchronization Thread test class *@authorXCX * @time July 21, 2017 morning 10:44:10*/ Public classTest { Public Static voidMain (string[] args) {//Create a Basket objectBasket Basket =NewBasket (); //creating producer and consumer threadsProducer Producer =NewProducer (basket); Consumer Consumer=NewConsumer (basket); Thread T1=NewThread (producer); Thread T2=NewThread (consumer); T1.start (); T2.start (); }}
Java Learning (7): Problems of producers and consumers of synchronization issues