Public classProducerconsumer { Public Staticvoid Main (String[] args) {Syncstack SS=NewSyncstack (); Producer P=NewProducer (ss); Consumer C=NewConsumer (ss); NewThread (P).start (); NewThread (P).start (); NewThread (P).start (); NewThread (c).start (); }} //defines a Wotou class that has an ID in the class to mark which of the TOU, overriding the ToString methodclassWotou {int id; Wotou (int id) { this. ID =ID; } Public StringtoString () {return"Wotou:" +ID; }} //defines a basket of objects for loading Wotou, a push method in the class, for the Wotou,pop method, for eating Wotouclasssyncstack {int index= 0; Wotou[] ARRWT=NewWotou[6]; /**wate () can only be used when locked (synchronized)*/ //push is used to load the Wotou when the Wotou number reaches 6 o'clock wait () rest Publicsynchronized void push (Wotou wt) { while(Index = = ARRWT.length) { Try{ This.wait (); } Catch(Interruptedexception e) {e.Printstacktrace (); } } //Wake-up Watt ()This.Notifyall (); Arrwt[index]=wt; Index++; } //pop used to eat Wotou, when Wotou number is 0 o'clock wait () Publicsynchronized Wotou pop () { while(Index = = 0) { Try{ This.wait (); } Catch(Interruptedexception e) {e.Printstacktrace (); }} this.Notifyall (); Index--; returnArrwt[index]; }} //inherit the Runnable interface, implement the producer class of the Run method, an object that only produces 20 WotouclassProducerImplementsRunnable {syncstack ss=NULL; Producer (Syncstack ss) { this. SS =SS; } Publicvoid Run () { for(int i=0; i<20; i++) {Wotou wt=NewWotou (i); SS.push (WT);System. Out.println ("produced:" +wt); Try{Thread.Sleep((Int.) (Math.random () * 200)); } Catch(Interruptedexception e) {e.Printstacktrace (); } } }} //inherits the Runnable interface, implements the consumer class of the Run method, and consumes only 20 Wotou of an objectclassConsumerImplementsRunnable {syncstack ss=NULL; Consumer (Syncstack ss) { this. SS =SS; } Publicvoid Run () { for(int i=0; i<20; i++) {Wotou wt= ss.pop ();System. Out.println ("Consumed:" +wt); Try{Thread.Sleep((Int.) (Math.random () * 1000)); } Catch(Interruptedexception e) {e.Printstacktrace (); } } }}
Teacher Ma's Wotou production and consumption thread explanation example